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.

3 Comments

  1. Peter payne wrote:

    Just wanted to say thanks for this excellent example!

    Saturday, May 1, 2010 at 1:17 am | Permalink
  2. Rob wrote:

    Awesome! This really helped me out. Thanks.

    Friday, May 14, 2010 at 8:17 am | Permalink
  3. 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

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*

Creative Commons Attribution 3.0 Unported
This work is licensed under a Creative Commons Attribution 3.0 Unported.