Skip to content

Instantly share code, notes, and snippets.

@JMichaelTX
Last active February 26, 2016 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JMichaelTX/36d6a5fff02b40d1f327 to your computer and use it in GitHub Desktop.
Save JMichaelTX/36d6a5fff02b40d1f327 to your computer and use it in GitHub Desktop.
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