Search-Replace Text

OK. This is a very basic routine. I’ll include it here, since many people doesn’t know about its existence.
As a little add-on, this routine supports also lists of search/replace terms.

For more powerful operations (eg, regular expressions, lots of MB of text to search-in, etc.), take a look to the Satimage osax or any shell utility (grep, etc.).

OS version: Any

(*
searchReplaceText(searchTerm, replaceTerm, theText)
Replaces a string found in a text by another string.
This handle supports lists of search/replace terms.

Parameters:
searchTerm: the text to search for
replaceTerm: the text to use as replacement
theText: the text to search/replace

Examples:
searchReplaceText("foo", "bar", "You are a foo") --> "You are a bar"
searchReplaceText({"foo", " a "}, {"bar", " one "}, "You are a foo") --> "You are one bar"
*)

to searchReplaceText(searchTerm, replaceTerm, theText)
	set searchTerm to searchTerm as list
	set replaceTerm to replaceTerm as list
	set theText to theText as text
	
	set oldTID to AppleScript's text item delimiters
	repeat with i from 1 to count searchTerm
		set AppleScript's text item delimiters to searchTerm's item i
		set theText to theText's text items
		set AppleScript's text item delimiters to replaceTerm's item i
		set theText to theText as text
	end repeat
	set AppleScript's text item delimiters to oldTID
	
	return theText
end searchReplaceText