Hi
im new to applescript (in fact, im new to mac) and i wonder,
what function can i use to replace a character in a certain string?
for example, i would like to replace the “:” in “12:00:00” to a “.”
thanks.
Hi
im new to applescript (in fact, im new to mac) and i wonder,
what function can i use to replace a character in a certain string?
for example, i would like to replace the “:” in “12:00:00” to a “.”
thanks.
One way is to use text item delimiters to do a search and replace. Here’s an example.
set x to SaR("12:00:00", ":", ".")
on SaR(sourceText, findText, replaceText)
set {atid, AppleScript's text item delimiters} to {AppleScript's text item delimiters, findText}
set tempText to text items of sourceText
set AppleScript's text item delimiters to replaceText
set sourceText to tempText as string
set AppleScript's text item delimiters to atid
return sourceText
end SaR
The other, less efficient way is to use offset:
set x to "12:00:00"
set y to 0
repeat
set C to characters of x
set y to offset of ":" in x
if y = 0 then exit repeat
set item y of C to "."
set x to C as string
end repeat
Thanks for the replies, its been a big help.
Here is one more example.
set theText to "12:00:00"
set replacedText to do shell script "echo " & quoted form of theText & " | sed 's/:/\\./g'"
How it works.
We feed theText into sed which is a UNIX utility.
sed does a replace using /to_replace/replace_with/ syntax
I put the “:” between the first / and
the “.” between the second /\./ The two \ characters
are to let sed know to substitute an actual “.”
instead of a wild-card character which it usually is.
The “g” at the end tells sed to replace “:” everywhere
it finds it and not just the first one.
Cheers,
Craig