DEV Community


Posted on

Everything About JavaScript String.prototype.replace() Method

Replacing text in a string is a very common task and with the help of replace() method available on String.prototype, we can do it very easily.


const newString = str.replace(regExp|substring , newSubstring|function)

The replace() method takes two arguments, first argument can be a string or regular expression and the second argument can either be a replacement string or a function whose return value will then be taken as replacement string.

Strings are immutable in JavaScript. That's why replace() returns a new string

The simplest use-case of this method is just by providing a string to match as first argument and a replacement string as second argument.

let str = 'I Love Java';

console.log(str.replace('Java', 'JavaScript')); // Expected Output: I Love JavaScript

Replace operations can be easily chained.

let str = 'I Love Java';
let str2 = str.replace('Java', 'JavaScript')
              .replace('JavaScript', 'Pizza');
console.log(str2); // I Love Pizza

In the replace string we can use special replacement patterns, for example we can use $& to insert the match.

let myStr = 'Java is Awesome'
console.log(myStr.replace('Java', '$&Script')) // JavaScript is Awesome

Some other replacement patterns:

  • $$ - Inserts a "$".
  • $` - Inserts the portion of the string that precedes the matched substring.
  • $' - Inserts the portion of the string that follows the matched substring.

There is also a pattern $n which inserts the nth match, but for this to work we have to use regular expression to match the string as explained in the next section.

Using Regular Expressions as first argument in replace()

Matching an exact string is good, but most of the times we find ourselves needing to match a pattern instead. It can easily be done by using a regular expression as the first argument.

In the following example, the regular expression is defined in replace().

let str = 'A Quick Brown Fox'
let newstr = str.replace(/brown/i, 'white')
console.log(newstr) // A Quick white Fox

In the above regular expression we used i flag. This flag ignores the case.

Checkout this guide by MDN to learn more about regular expresssions.

Let's take another example to show the use of $n replacement pattern.

let str = 'Regular Expressions';
let regex = /(\w+)\s(\w+)/;
let newstr = str.replace(regex, '$1 $2 are evil');
console.log(newstr); // Regular Expressions are evil
  • /(\w+)\s(\w+)/ - This regex matches two words separated by a space character.
  • $1 will be equal to whatever first capturing group (regex inside the parenthesis) captures, in our case its the string 'Regular'.
  • Similarly $2 will be equal to the result to second capturing group which is 'Expressions'.
  • In the end we use $1 , $2 to create new string.

Using a Function as a second argument in replace()

We can use a function as a second argument for replace(), this function is known as Replacer Function. This function is invoked after the match has been performed. This function's result (return value) will be used as the replacement string.

The various possible arguments of this function are discussed below:

  • match - The matched string.
  • p1, p2, ... - The nth string found by a parenthesized capture group, provided the first argument to replace() was a RegExp object. For example, if /(\w+)(\d+)/, was given, p1 is the match for \w+, and p2 for \d+.
  • offset - The offset (index) of the matched string within the whole string being examined. (For example, if the whole string was 'abcd', and the matched string was 'bc', then this argument will be 1.)
  • originalString - The full string.

Let's see it in action through an example.

function replacerFunction(match, p1, p2, offset, originalString) {
    return (p1 - 1) + (p2);

let myStr = '99 Bottles Of Bear On The Wall';
let regex = /(\d{2})(\w*)/;
let newStr = myStr.replace(regex, replacerFunction);

console.log(newStr); // 98 Bottles Of Bear On The Wall

In above example our first capture group matches the digit '99' and second one matches the rest of the string. After that the replacer function return the modified result.

Let's see how to create a very-very simple and silly url slug generator using replace().

let title = 'My Awesome Post';

let urlSlug = title.replace(/(\w+)\s(\w+)\s(\w+)/, function (match, p1, p2, p3) {
  return `${p1}-${p2}-${p3}`;

console.log(urlSlug); // My-Awesome-Post

Aaaand That's all. I hope you learned something useful from this post. If anything is not clear, let me know in comments. :)

Top comments (0)