Created
November 8, 2017 18:06
-
-
Save masnick/93831b882036b7fc1a7f9478513b1c74 to your computer and use it in GitHub Desktop.
Trim whitespace with AppleScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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