Replaces text in a string, using a regular expression or search string.
SyntaxstringObj. replace( rgExp , replaceText )
The result of the replace method is a copy of stringObj after the specified replacements have been made.
RemarksAny of the following match variables can be used to identify the most recent match and the string from which it came. The match variables can be used in text replacement where the replacement string has to be determined dynamically.
Characters Meaning $$ $ (Internet Explorer 5.5 or later) $& Specifies that portion of stringObj that the entire pattern matched. (Internet Explorer 5.5 or later) $` Specifies that portion of stringObj that precedes the match described by $&. (Internet Explorer 5.5 or later) $’ Specifies that portion of stringObj that follows the match described by $&. (Internet Explorer 5.5 or later) $ n The n th captured submatch, where n is a single decimal digit from 1 through 9. (Internet Explorer 5.5 or later) $ nn The nn th captured submatch, where nn is a two-digit decimal number from 01 through 99. (Internet Explorer 5.5 or later)If replaceText is a function, for each matched substring the function is called with the following m + 3 arguments where m is the number of left capturing parentheses in the rgExp. The first argument is the substring that matched. The next m arguments are all of the captures that resulted from the search. Argument m + 2 is the offset within stringObj where the match occurred, and argument m + 3 is stringObj. The result is the string value that results from replacing each matched substring with the corresponding return value of the function call.
The replace method updates the properties of the global RegExp object.
ExamplesThe following example illustrates the use of the replace method to replace all instances of “the” with “a.”
var s = "the batter hit the ball with the bat";
var re = /the/g;
var result = s.replace(re, "a");
document.write(result);
In addition, the replace method can also replace subexpressions in the pattern. The following example exchanges each pair of words in the string.
var s = "The quick brown fox jumped over the lazy dog.";
var re = /(\S+)(\s+)(\S+)/g;
var result = s.replace(re, "$3$2$1");
document.write(result);
The following example, which works in JavaScript 5.5 and later, shows how to use a function that returns the replacement text. It replaces any instance of a number followed by “F” with a Celsius conversion.
function f2c(s1) {
var test = /(\d+(\.\d*)?)F\b/g;
var s2 = s1.replace(test,
function($0,$1,$2)
{
return((($1-32) * 5/9) + "C");
}
)
return s2;
}
document.write(f2c("Water freezes at 32F and boils at 212F."));
See also Other articles
Microsoft Developer Network: Article
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4