Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does AppleScript have a replace function?

Tags:

applescript

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.

like image 214
potapeno Avatar asked Jun 26 '16 18:06

potapeno


People also ask

Is replace () a function?

What is the REPLACE Function? The REPLACE Function[1] is categorized under Excel TEXT functions. The function will replace part of a text string, based on the number of characters you specify, with a different text string.

How replace function is used?

Returns a String in which a specified substring has been replaced with another substring a specified number of times. Required. String expression containing substring to replace.

What is an AppleScript?

AppleScript is a scripting language that was developed by Apple Inc. It was designed to allow users of the Apple operating system make work easier, such as automating repetitive operations. AppleScript uses coding syntax that is mostly comprised of regular words, which makes it easier for a non-programmer to read.


2 Answers

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")

like image 122
mb21 Avatar answered Sep 27 '22 17:09

mb21


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
like image 21
PHennessey Avatar answered Sep 27 '22 16:09

PHennessey