Skip to content

An AppleScript Replace Text Method

Bruce Phillips, one of the leading posters at MacScripter, posted a very useful method on his blog which you can use to find and replace text in a variable. Below is the code he created and an example so you can test it in the Script Editor.

on replaceText(find, replace, subject)
	set prevTIDs to text item delimiters of AppleScript
	set text item delimiters of AppleScript to find
	set subject to text items of subject
	
	set text item delimiters of AppleScript to replace
	set subject to "" & subject
	set text item delimiters of AppleScript to prevTIDs
	
	return subject
end replaceText

get replaceText("Windows", "the Mac OS", "I love Windows and I will always love Windows and I have always loved Windows.")

Mr. Phillips has over 2500 postings at MacScripter and one can learn a lot from browsing through them to see the various solutions he has proposed to people’s problems.

4 Comments

  1. Fabrice wrote:

    Hi,

    thank you for this excellent script.
    I am actually trying to do the same but base on arrays.
    I’d like to do multiple substitution in one go.
    I could surely use a loop, but it’s rather slow (we’re talking about several hundreds of items)
    Thanks again!

    Thursday, September 30, 2010 at 10:36 am | Permalink
  2. Whizzbizz wrote:

    Finally a simple solution to my text scripting “problem”.

    Thank you!

    Monday, February 20, 2012 at 6:47 am | Permalink
  3. Whizzbizz wrote:

    …and I promise: I will always love the Mac!

    Monday, February 20, 2012 at 6:48 am | Permalink
  4. Montana wrote:

    Might I suggest a small edit? How about telling the function to throw an error if it did not find any instances of the string to be replaced? I wrote “set originalString to subject” at the top of the function. At the bottom, I wrote:
    “if subject is originalString then
    error find & ” is not in the subject string.”
    end if

    Wednesday, January 16, 2013 at 12:14 am | Permalink