Does anyone have a snippet of code that will let me remove just the ending white space from a string.
For example:
Take this string "File "
and make it “File”
Thanks
Does anyone have a snippet of code that will let me remove just the ending white space from a string.
For example:
Take this string "File "
and make it “File”
Thanks
This works. I found the basis for it on MacOSXHints
set theString to "File "
if length of theString > 0 then
repeat
if not (ASCII number of the last character of theString) = 32 then
exit repeat
end if
--else remove character
set theString to characters 1 through ((length of theString) - 1) of theString as string
end repeat
return "::" & theString & "::"
You could do this also:
set na to "File "
set tid to text item delimiters
set text item delimiters to " "
set n to first text item of na
set text item delimiters to tid
return n
PreTech
Assuming that it’s spaces and not some other characters that are just not able to be displayed, somethign like this should work…
set theString to "here is some text "
stripTrailingSpace(theString)
to stripTrailingSpace(theInput)
if theInput ends with " " then
set theOutput to (characters 1 through -2 of theInput) as string
stripTrailingSpace(theOutput)
else
return theInput
end if
end stripTrailingSpace
j
Here’s another idea:
on stripTrailingSpace(someText)
local someText
repeat until someText does not end with " "
set someText to text 1 thru -2 of someText
end repeat
end stripTrailingSpace
(On my machine, it’s about twice as fast as jobu’s; that’s probably due to the list-to-string coerion.)
I seemed to have problems with “character” in AppleScript Studio so I changed the scripts to this:
on removeStartingSpace(thisField)
set thisField to thisField as string
repeat
set firstCharacter to (ASCII number of character 1 of thisField)
if firstCharacter = 32 then
--remove space
set thisField to (text 2 thru end of thisField) as string
else
-- if first character isn't a space then done
exit repeat
end if
end repeat
return thisField
end removeStartingSpace
on removeTrailingSpace(thisField)
set thisField to thisField as string
repeat
set lastCharacter to (ASCII number of last character of thisField)
if lastCharacter = 32 then
--remove white space
set thisField to text 1 thru ((length of thisField) - 1) of thisField as string
else
--done
exit repeat
end if
end repeat
return thisField
end removeTrailingSpace
Why look up the ascii number of the character? (That’s way slower on my machine.)
This seems to work fine:
on trim(someText)
repeat until someText does not start with " "
set someText to text 2 thru -1 of someText
end repeat
repeat until someText does not end with " "
set someText to text 1 thru -2 of someText
end repeat
return someText
end trim
trim("Hello World ")