What should be a simple piece of code to remove the last character from a string seems to be breaking for no apparent reason (to me anyway).
I am trying to create a simple script to fix colleagues OneDrive file sync problems when they have extra spaces around filenames and extensions.
Coming back to AppleScript after a very long time away and seem to have forgotten everything, just need to understand why what should be simple seems to have me baffled... be gentle with me.
on stripSpaces(thisText)
local newText
local pos
local tempText
set newText to thisText
set tempText to ""
repeat while tempText ≠ newText
set tempText to newText
--remove spaces before extension name
set pos to the offset of ". " in newText
if pos > 0 then
set newText to ((characters 1 thru pos of newText) as text) & (characters (pos + 2) thru end of newText) as text
end if
--remove spaces before extension
set pos to the offset of " ." in newText
if pos > 0 then
set newText to ((characters 1 thru (pos - 1) of newText) as text) & (characters (pos + 1) thru end of newText) as text
end if
--remove leading spaces
if character 1 of newText = " " then
set newText to characters 2 thru end of newText as text
end if
---BROKEN SECTION
--remove trailing spaces
if (last character of newText) = " " then
set newText to (characters 1 thru (end of newText) - 1) as text
end if
end repeat
return newText
end stripSpaces
log stripSpaces(" spa . nish . txt ")
error "Can’t get end of \" spa . nish . txt \"." number -1728 from last insertion point of " spa . nish . txt "
stripSpacessub-routine could be replaced with the following one line instead:return do shell script "str=" & quoted form of thisText & "; echo \"${str// /}\""