10

In VBA, its extrememly easy to replace substrings with a different substring, an example being objMsg.Body = Replace(objMsg.Body, "<Month\", Format(dtDate1, "mmmm")) which replaces "<Month>" with the current month in a email body. I've seen questions similar to this before, but they are a couple years old and tend to have insane workarounds that are almost not even worth my time.

2 Answers 2

14

No, but you can use this one (source):

on replace_chars(this_text, search_string, replacement_string)
 set AppleScript's text item delimiters to the search_string
 set the item_list to every text item of this_text
 set AppleScript's text item delimiters to the replacement_string
 set this_text to the item_list as string
 set AppleScript's text item delimiters to ""
 return this_text
end replace_chars

usage:

replace_chars(message_string, "string_to_be_replaced", "replacement_string")

(btw, you can nowadays also use JavaScript instead of AppleScript, search for "JavaScript for OS X Automation")

3
  • ++, but in the interest of robustness it is better to save and restore the original text item delimiter value.
    – mklement0
    Jun 26, 2016 at 20:02
  • 1
    @potapeno: As long as you know how the function works (case-INsensitive replacement of ALL occurrences; wrap calls in a considering case ... end considering block for case-SENSITIVE matching), you don't need to understand it. That said, fundamentally switching to JXA (JavaScript for Automation), available since 10.10, may make you happier, though it seems to be an only slightly less unwanted stepchild than AppleScript
    – mklement0
    Jun 26, 2016 at 20:05
  • 3
    The problems with JXA are virtually zero documentation, examples, or user support, and numerous design defects and omissions in its Apple event bridge and OSA component plugin support. If you're doing application scripting then AppleScript is the only officially supported option that works right. Couple links that may help: I'm giving away an AS "standard lib" to anyone that wants it, and a how-to for calling AS handlers from other languages via the AppleScript-ObjC bridge.
    – foo
    Jun 29, 2016 at 11:04
3

One really simple way to do find/replace is to call a shell script and pass text into it as a string:

set inputText to "My name is Fred."
set findText to "Fred"
set replaceText to "Sally"

set newText to do shell script "sed 's|" & quoted form of findText & "|" & quoted form of replaceText & "|g' <<< " & quoted form of inputText
1
  • 1
    Btw the replaceText must also be Regex safe, so no " " Jul 8, 2016 at 17:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.