Shorten string for usage as filename?

Hi, I’d like to shorten a string to use it as filename and preserve as much of the string as possible.

Ended up trying to rebuild a Objective-C solution I found on stackoverflow. I think this uses the NSData Instance Property bytes.

- (NSString *)fetchStringWithOriginalString:(NSString *)originalString withByteLength:(NSUInteger)length
    NSData* originalData=[originalString dataUsingEncoding:NSUTF8StringEncoding];
    const char *originalBytes = originalData.bytes;

    //make sure to use a loop to get a not nil string.
    //because your certain length data may be not decode by NSString
    for (NSUInteger i = length; i > 0; i--) {

        @autoreleasepool {
            NSData *data = [NSData dataWithBytes:originalBytes length:i];
            NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            if (string) {
                return string;

    return @"";

Here’s what doesn’t work.
Note: The “|bytes|()” line crashes Script Debugger (obviously one shouldn’t do that).

use AppleScript version "2.4"
use framework "Foundation"
use scripting additions

set theName to "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"

set originalString to (current application's NSString's stringWithString:theName)
set originalData to (originalString's dataUsingEncoding:(current application's NSUTF8StringEncoding))

#set originalBytes to originalData's |bytes|() -- this crashes Script Debugger
set originalLength to originalData's |length|()

#if (originalBytes as integer) > 255 then
if (originalLength as integer) > 255 then
	repeat with i from 255 to 0 by -1
		#set |data| to (current application's NSData's dataWithBytes:originalBytes |length|:(i))
		set |data| to (current application's NSData's dataWithBytes:originalData |length|:(i))
			set |string| to (current application's NSString's alloc()'s initWithData:(|data|) encoding:(current application's NSUTF8StringEncoding))
			if |string| ≠ missing value then
				return |string|
			end if
		end try
	end repeat
end if

After trying far too long I searched in “Everyday AppleScriptObjC” and now guess that it’s not possible to use that Instance Property in AppleScriptObjC.

If so, how can I shorten a string for a filename?

ASObjC can’t deal in raw data, just NSData.

You might do better using lengthOfBytesUsingEncoding:, and stripping off characters in native AppleScript until you get the value you need.

1 Like

That did it. Thanks!