Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AppleScript Trim Function / Handler Using ASObjC (Shane Stanley)
###BEGIN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# trimThis() Trim (remove) Characters from Left and/or Right of String
#
# Ver 1.1 2016-02-25
# AUTHOR: Shane Stanley
# (minor revisions by JMichaelTX)
# REF: MacScripter / Trim [Remove Spaces]
# http://macscripter.net/viewtopic.php?pid=182209#p182209
# PARAMETERS:
# • pstrCharToTrim : A list of characters to trim, or true to use default
# • pstrSourceText : The text to be trimmed
# • pstrTrimDirection : Direction of Trim left, right or any value for full
###——————————————————————————————————————————————————————————————————————————————————
on trimThis(pstrSourceText, pstrCharToTrim, pstrTrimDirection)
--- SET CHARACTERS TO TRIM ---
if pstrCharToTrim = missing value or pstrCharToTrim = true then
-- SPACE, TAB, RETURN, newline characters (U+000A–U+000D, U+0085)
-- Equiv to: ASCII character 10, return, ASCII character 0
set setToTrim to current application's NSCharacterSet's whitespaceAndNewlineCharacterSet()
else
set setToTrim to current application's NSCharacterSet's characterSetWithCharactersInString:pstrCharToTrim
end if
set anNSString to current application's NSString's stringWithString:pstrSourceText
--- TRIM STRING BASED ON REQUESTED DIRECTION ---
if pstrTrimDirection = left then -- FROM LEFT SIDE OF STRING
set theRange to anNSString's rangeOfCharacterFromSet:(setToTrim's invertedSet())
if |length| of theRange = 0 then return ""
set anNSString to anNSString's substringFromIndex:(theRange's location)
else if pstrTrimDirection = right then -- FROM RIGHT SIDE OF STRING
set theRange to anNSString's rangeOfCharacterFromSet:(setToTrim's invertedSet()) options:(current application's NSBackwardsSearch)
if |length| of theRange = 0 then return ""
set anNSString to anNSString's substringToIndex:(theRange's location)
else -- FROM BOTH SIDES OF STRING
set anNSString to anNSString's stringByTrimmingCharactersInSet:setToTrim
end if
return anNSString as text
end trimThis
###END~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment