replace()
method accepts two arguments.
RegExp
object or a string.If the first argument is a string, then only the first occurrence is replaced. To replace all instances of a substring, you have to provide a regular expression with the global flag.
This method does not change the original string.
replace() |
Yes | Yes | Yes | Yes | Yes |
stringObject.replace(sourceValue, newValue);
Parameter | Description |
---|---|
sourceValue | Required. The value, or regular expression, to be replaced by the new value |
newValue | Required. The value to replace the sourceValue with |
A new result string.
var text = "doom, room, loom";
var result = text.replace("oo", "aa");
console.log(result); //daam, room, loom
result = text.replace(/oo/g, "aa");
console.log(result); // daam, raam, laam
The code above generates the following result.
If the second argument is a string, there are several special character sequences that can be used to insert values from the regular-expression operations.
Sequence | Replacement Text |
---|---|
$$ | $ |
$& | The substring matching the entire pattern. |
$' | The part of the string occurring before the matched substring. |
$` | The part of the string occurring after the matched substring. |
$n | nth capture, where n is a value 0-9. |
$nn | nnth capture, where nn is a value 01-99. |
Using these special sequences allows replacement using information about the last match, such as in this example:
var text = "room, loom, doom";
result = text.replace(/(.oo)/g, "aa ($1)");
console.log(result); //aa (roo)m, aa (loo)m, aa (doo)m
The code above generates the following result.
The following code shows the usage of $'
.
var text = "room, loom, doom";
result = text.replace(/(.oo)/g, "aa ($')");
console.log(result);
//aa (m, loom, doom)m, aa (m, doom)m, aa (m)m
The code above generates the following result.
The second argument of replace() may be a function. When there is a single match, the function gets passed three arguments:
When there are multiple matches, the function gets passed three arguments:
The function returns a string indicating what the match should be replaced with.
function htmlEscape(text){ // w ww .j a v a2 s. c o m
return text.replace(/[<>"&]/g, function(match, pos, originalText){
switch(match){
case "<":
return "<mark><</mark>";
case ">":
return "<mark>></mark>";
case "&":
return "<mark>&</mark>";
case "\"":
return "<mark>"</mark>";
}
});
}
console.log(htmlEscape("<p class='greeting'>Hello world!</p>"));
The code above generates the following result.