Javascript String replace()

Introduction

To replacing substrings, use Javascript replace() method.

The original string is left unchanged.

var newStr = str.replace(regexp|substr, newSubstr|function)
  • regexp(pattern) - a RegExp object or literal.
  • substr(pattern) - a String to be replaced by newSubStr.
  • newSubStr(replacement) - the String that replaces the substring
  • function(replacement) - a function to be invoked to create the new substring

This method accepts two arguments.

The first argument can be a RegExp object or a string.

The second argument can be a string or a function.

If the first argument is a string, then only the first occurrence of the substring will be replaced.

To replace all instances of a substring, use a regular expression with the global flag specified:

let text = "cat, bat, sat, fat";     
let result = text.replace("at", "an"); 
console.log(result);  //from  ww  w  .  j  a  v a 2  s.  c  o  m

result = text.replace(/at/g, "an"); 
console.log(result);  

When the second argument is a string, we can use special character sequences to insert values from the regular-expression operations.

ECMA-262 specifies the following table of values.

SEQUENCE REPLACEMENT TEXT
$$ $
$& The substring matching the entire pattern. Same as RegExp.lastMatch.
$' The part of the string occurring before the matched substring. Same as RegExp.rightContext
$` The part of the string occurring after the matched substring. Same as RegExp.leftContext
$n The nth capture, where n is a value 0-9. For instance, $1 is the first capture, $2 is the second, and so on. If there is no capture then the empty string is used.
$nn The nnth capture, where nn is a value 01-99. For instance, $01 is the first capture, $02 is the second, and so on. If there is no capture then the empty string is used.

Using these special sequences allows replacement using information about the last match:

let text = "cat, bat, sat, fat";     
result = text.replace(/(.at)/g, "an ($1)"); 
console.log(result);  /*from   w w w.j  ava  2s.  co m*/

Here, each word ending with "at" is replaced with "an" followed in parentheses by what it replaces by using the $1 sequence.

The second argument of replace() may be a function.

When there is a single match, the function gets passed three arguments:

  • the string match
  • the position of the match within the string
  • the whole string.

When there are multiple capturing groups, each matched string is passed in as an argument.

The last two arguments are the position of the pattern match in the string and the original string.

The function should return a string indicating what the match should be replaced with.

function htmlEscape(text) {
    return text.replace(/[<>"&]/g, function(match, pos, originalText) {
        switch (match) {
            case "<":
                return "&lt;";
            case ">":
                return "&gt;";
            case "&":
                return "&amp;";
            case "\"":
                return "&quot;";
        }//w  w  w.ja v a2  s  .  c o m
    });
}
console.log(htmlEscape("<p class=\"greeting\">Hello world!</p>"));

You can specify a function as the second parameter.

The function is invoked after the match is found.

The function's return value is used as the replacement string.

The arguments to the function are as follows:

Possible name Supplied value
match The matched substring.
p1, p2, ... The nth string found by a parenthesized capture group
offsetThe offset of the matched substring
stringThe whole string being examined.
function replacer(match, p1, p2, p3, offset, string) {
  return [p1, p2, p3].join(' - ');
}
var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
console.log(newString);  // abc - 12345 - #$*%

Switching words in a string

var re = /(\w+)\s(\w+)/;
var str = 'John Smith';
var newstr = str.replace(re, '$2, $1');
console.log(newstr);  // Smith, John



PreviousNext

Related