On Jul 25, 2011, at 11:10 AM, Zavatone, Alex wrote:
Hi. I've got a little not so elegant script to trim spaces from the beginning of a line. It handles if the whole line is full of spaces, but I was wondering if anyone out there has anything faster and is willing to share.
Inelegant indeed.
on TrimSpacesFromStartOfLine(myText)
set i to 1
set len to length of myText
repeat while i ≤ len and character i of myText = " "
set i to i + 1
end repeat
if i > len then
return ""
else
return text i thru len of myText
end if
end TrimSpacesFromStartOfLine
set rslt to {}
repeat with aText in {"", " ", " junk and more ", "normal"}
set end of rslt to {contents of aText, TrimSpacesFromStartOfLine(aText)}
end repeat
rslt
Be sure to test ALL of the edge cases:
myText is the empty string
myText is one or more spaces
myText is not all spaces, but begins with one
myText begins with a non-space
Many of the contributions on this thread fail when myText is the empty string, usually because they look at "character 1 of myText" without checking that myText has a character 1.
Some contributions return myText unchanged if it begins with a non-space, but what if the actual parameter is "paragraph 3 of …" and you use the result later when the … has been changed to have a different third paragraph?