String.replace( searchExpr, replaceExpr ) in ECMAScript Core
Find and replace values in a string, and return the changed string.
Arguments
name | type | description |
---|---|---|
searchExpr | Object | Either a literal String or Regular Expression to search for. |
replaceExpr | Object | Either a String value to replace each found instance with, or a function which returns a String to replace each found instance with (see below) |
- Return Type
- String
Description
If searchExpr
is a string, a case-sensitive search is performed, and only the first match found is replaced. To make a case-insensitive replacement or global replacement, use a regular expression for the search expression.
var sentence = "The quick brown fox and the duck jump over the lazy dog.";
var oneReplaced = sentence.replace( 'the' , '**the**' );
var allReplaced = sentence.replace( /the/gi , '**the**' );
// ** oneReplaced is "The quick brown fox and **the** duck jump over the lazy dog."
// ** allReplaced is "**the** quick brown fox and **the** duck jump over **the** lazy dog."
When searchExpr
is a regular expression and replaceExpr
is a string, the following substrings have special meaning:
- $&
- The entire matched substring.
- $?
- The portion of the original string that precedes the matched substring.
- $?
- The portion of the original string that follows the matched substring
- $n
- The nth captured subexpression, where n is a single digit and $n is not followed by another digit.
- $nn
- The nnth captured subexpression, where nn is a two-digit number.
- $$
- Replace with a literal "$"
var sentence = "The quick brown fox jumps over the lazy dog.";
var blankouts = sentence.replace( /\b([a-z])[a-z]+/gi , '$1****' );
// ** alternatedBlankouts is "T**** q**** b**** f**** j**** o**** t**** l**** d****."
If replaceExpr
is a function, it will be passed the following arguments, in order:
- The substring that was matched.
- If
searchExpr
is a regular expression, one argument for each parentheses-captured substring in the expression will be passed. - The next-to-last argument will be the index in the source string where the match occurred.
- The last argument passed is the entire source string.
var sourceString = "It's the end of the world as we know it, and I feel fine.";
function SwapCharacterPairs(str,sub1,sub2,index,srcString){
return sub2+sub1;
}
var newString = sourceString.replace( /(.)(.)/g , SwapCharacterPairs );
// ** newString is "tIs't ehe dno fht eowlr dsaw enkwoi ,ta dnI f ee lifen.";
var prices = "Items cost stuff. Candy: $.50; Glasses: $3.75; 500 pages: $4.99";
var priceRE = /\$(\d*(\.\d{2})?)/g;
function IncreasePrice(str,price){
// all the extra parameters that we don't need are ignored
return '$'+Math.round(price*1.66*100)/100;
}
var newPrices = prices.replace(priceRE,IncreasePrice);
// ** newPrices is "Items cost stuff. Candy: $0.83; Glasses: $6.23; 500 pages: $8.28"