Core JavaScript 1.5 Reference:Global Objects:String:replace
From MDC
Contents |
[edit] Summary
Finds a match between a regular expression and a string, and replaces the matched substring with a new substring.
| Method of String | |
| Implemented in: | JavaScript 1.2
JavaScript 1.3 added the ability to specify a function as the second parameter. |
| ECMAScript Edition: | ECMA-262 Edition 3 |
[edit] Syntax
var newString = str.replace(regexp/substr, newSubStr/function[, flags]);
[edit] Parameters
-
regexp - A RegExp object. The match is replaced by the return value of parameter #2.
-
substr - A String that is to be replaced by
newSubStr.
-
newSubStr - The String that replaces the substring received from parameter #1.
-
function - A function to be invoked to create the new substring (to put in place of the substring received from parameter #1).
-
flags - (SpiderMonkey extension) A String containing any combination of the RegExp flags:
g- global match,i- ignore case,m- match over multiple lines. This parameter is only used if the first parameter is a string.
[edit] Description
This method does not change the String object it is called on. It simply returns a new string.
To perform a global search and replace, either include the g flag in the regular expression or if the first parameter is a string, include g in the flags parameter.
[edit] Specifying a string as a parameter
The replacement string can include the following special replacement patterns:
| Pattern | Inserts |
$$ |
Inserts a "$". |
$& |
Inserts the matched substring. |
$` |
Inserts the portion of the string that precedes the matched substring. |
$' |
Inserts the portion of the string that follows the matched substring. |
$n or $nn |
Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object. |
[edit] Specifying a function as a parameter
When you specify a function as the second parameter, the function is invoked after the match has been performed. (The use of a function in this manner is often called a lambda expression.)
In your function, you can dynamically generate the string that replaces the matched substring. The result of the function call is used as the replacement value.
The nested function can use the matched substrings to determine the new string (newSubStr) that replaces the found substring. You get the matched substrings through the parameters of your function. The first parameter of your function holds the complete matched substring. If the first argument was a RegExp object, then the following n parameters can be used for parenthetical matches, remembered submatch strings, where n is the number of submatch strings in the regular expression. Finally, the last two parameters are the offset within the string where the match occurred and the string itself. For example, the following replace method returns XXzzzz - XX , zzzz.
function replacer(str, p1, p2, offset, s)
{
return str + " - " + p1 + " , " + p2;
}
var newString = "XXzzzz".replace(/(X*)(z*)/, replacer);
[edit] Examples
[edit] Example: Using global and ignore 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'.
var re = /apples/gi; var str = "Apples are round, and apples are juicy."; var newstr = str.replace(re, "oranges"); print(newstr);
In this version, a string is used as the first parameter and the global and ignore case flags are specified in the flags parameter.
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace("apples", "oranges", "gi");
print(newstr);
Both of these examples print "oranges are round, and oranges are juicy."
[edit] Example: Defining the regular expression in replace
In the following example, the regular expression is defined in replace and includes the ignore case flag.
var str = "Twas the night before Xmas..."; var newstr = str.replace(/xmas/i, "Christmas"); print(newstr);
This prints "Twas the night before Christmas..."
[edit] Example: Switching words in a string
The following script switches the words in the string. For the replacement text, the script uses the $1 and $2 replacement patterns.
var re = /(\w+)\s(\w+)/; var str = "John Smith"; var newstr = str.replace(re, "$2, $1"); print(newstr);
This prints "Smith, John".
[edit] Example: Using an inline function that modifies the matched characters
In this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just before the match location. The important thing here is that additional operations are needed on the matched item before it is given back as a replacement.
The replacement function accepts the matched snippet as its parameter, and uses it to transform the case and concatenate the hyphen before returning.
function styleHyphenFormat(propertyName)
{
function upperToHyphenLower(match)
{
return '-' + match.toLowerCase();
}
return propertyName.replace(/[A-Z]/, upperToHyphenLower);
}
Given styleHyphenFormat('borderTop'), this returns 'border-top'.
Because we want to further transform the result of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the toLowerCase() method. If we had tried to do this using the match without a function, the toLowerCase() would have no effect.
var newString = propertyName.replace(/[A-Z]/, '-' + '$&'.toLowerCase()); // won't work
This is because '$&'.toLowerCase() would be evaluated first as a string literal (resulting in the same '$&') before using the characters as a pattern.
[edit] Example: Replacing a Fahrenheit degree with its Celsius equivalent
The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with F. The function returns the Celsius number ending with C. For example, if the input number is 212F, the function returns 100C. If the number is 0F, the function returns -17.77777777777778C.
The regular expression test checks for any number that ends with F. The number of Fahrenheit degree is accessible to the function through its second parameter, p1. The function sets the Celsius number based on the Fahrenheit degree passed in a string to the f2c function. f2c then returns the Celsius number. This function approximates Perl's s///e flag.
function f2c(x)
{
function convert(str, p1, offset, s)
{
return ((p1-32) * 5/9) + "C";
}
var s = String(x);
var test = /(\d+(?:\.\d*)?)F\b/g;
return s.replace(test, convert);
}