Trim a string the Applescript way

I need to trim a string of whitespace left and right. At the moment I do it like this:

-- trim theName
repeat until first character of theName is not " "
    set theName to (characters 2 thru -1 of theName) as string
end repeat
repeat until last character of theName is not " "
    set theName to (characters 1 thru -2 of theName) as string
end repeat

Apart from the fact that it only cares for spaces (which I could fix with a ‘…is not SPACE and is not TAB and is not …’ construct), I think my solution is not very “applescriptonic”. Is there a way to make it more elegant, preferably with less code as well?

Any suggestions?

See here

Thanks for this. It is a good thread.

However all versions in the other thread are a lot longer! Some might be faster, but certinly not easier to read…

I was hoping for something which can magically tap into the “natural lanaguage capebilities” of Applescript… something like

set trimmed to texts without whitspace of theName 

:lol:

So for now I stick with the loop version…

That is:

words of theName

That only works if the name doesn’t contain any whitespaces in between. A complete solution is then:

set theName to " john "

-- make sure text item delimiters is set correctly
set oldTIDs to AppleScript's text item delimiters
set AppleScript's text item delimiters to ""
set theName to words of theName as string
set AppleScript's text item delimiters to oldTIDs

return theName

But as you pseudo example it will remove all whitespaces, not only the surrounding.

That’s cool. Thanks for the example!