Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
String
replace(regexp, newSubStr)
regexp
The name of the regular expression. It can be a variable name or a literal.
newSubStr
The string to put in place of the string found with regexp. This string can include the RegExp properties $1, ..., $9, lastMatch, lastParen, leftContext, and rightContext.
This method does not change the String object it is called on; it simply returns a new string.
If you want to execute a global search and replace, or a case insensitive search, include the g (for global) and i (for ignore case) flags in the regular expression. These can be included separately or together. The following two examples below show how to use these flags with replace.
In the following example, the regular expression includes the global and ignore case flags which permits replace to replace each occurrence of 'apples' in the string with 'oranges.'
re = /apples/gi; str = "Apples are round, and apples are juicy."; newstr=str.replace(re, "oranges"); Console.Write(newstr)
This prints "oranges are round, and oranges are juicy."
In the following example, the regular expression is defined in replace and includes the ignore case flag.
str = "Twas the night before Xmas..."; newstr=str.replace(/xmas/i, "Christmas"); Console.Write(newstr)
"Twas the night before Christmas..."
The following script switches the words in the string. For the replacement text, the script uses the values of the $1 and $2 properties.
"Smith, John"