Search and Replace

Regular expressions can also be used to replace parts of a string by a different string. In Studio, you can do this using the replace function. The first argument to replace is the regular expression search and the second argument is the new string. For example:
	myString = "We played 1 on 1" 
	myString.replace('/1/', "one") 
	
	display myString 
	
In the second line, 1 is replaced by one. Notice that only the first occurrence of 1 is replaced when you try the code with the debugger. In order to replace all occurrences, you must use the g modifier. For example:
	myString.replace('/1/g', "one") 
	
The following code strips any zero digit on the left end of a string. For example, to change 005422 to 5422, use:
	myString.replace('/\b0+/g', "")
	

A powerful feature of the replace function is that you can use backreferencing in the replacing string. You do so by using $x, where x is the grouping number.

For example, to swap the first two words in a string:
myString.replace('/(w+) (\w+)/', "$2 $1") 
To convert a MM-DD-YYYY date to DD/MM/YYYY, use:
	myString.replace('/(\d+)-(\d+)-(\d+)/', "$2/$1/$3") 
	
To remove quotes surrounding any word:
myString.replace('/"(\w+)"/g', "$1")