Skip to content

Instantly share code, notes, and snippets.

@masnick masnick/trim.scpt
Created Nov 8, 2017

Embed
What would you like to do?
Trim whitespace with AppleScript
on trimThis(pstrSourceText, pstrCharToTrim, pstrTrimDirection)
-- http://macscripter.net/viewtopic.php?id=18519
-- pstrSourceText : The text to be trimmed
-- pstrCharToTrim : A list of characters to trim, or true to use default
-- pstrTrimDirection : Direction of Trim left, right or any value for full
set strTrimedText to pstrSourceText
-- If undefinied use default whitespaces
if pstrCharToTrim is missing value or class of pstrCharToTrim is not list then
-- trim tab, newline, return and all the unicode characters from the 'separator space' category
-- [url]http://www.fileformat.info/info/unicode/category/Zs/list.htm[/url]
set pstrCharToTrim to {tab, linefeed, return, space, character id 160, character id 5760, character id 8192, character id 8193, character id 8194, character id 8195, character id 8196, character id 8197, character id 8198, character id 8199, character id 8200, character id 8201, character id 8202, character id 8239, character id 8287, character id 12288}
end if
set lLoc to 1
set rLoc to count of strTrimedText
--- From left to right, get location of first non-whitespace character
if pstrTrimDirection is not right then
repeat until lLoc = (rLoc + 1) or character lLoc of strTrimedText is not in pstrCharToTrim
set lLoc to lLoc + 1
end repeat
end if
-- From right to left, get location of first non-whitespace character
if pstrTrimDirection is not left then
repeat until rLoc = 0 or character rLoc of strTrimedText is not in pstrCharToTrim
set rLoc to rLoc - 1
end repeat
end if
if lLoc rLoc then
return ""
else
return text lLoc thru rLoc of strTrimedText
end if
end trimThis
set output to " test "
set output to trimThis(output, true, true)
return output
-- returns "test"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.