JavaScript replace() to make your life easy

Javascript replace() is an in-built method in a String object. The basic usage of the replace() method is to find a substring or a regular expression pattern in a string and replace it with another string or a function.

We are going to discuss the javascript replace() method in String object in detail in this post.

JavaScript replace() method : the Basic Usage

Syntax: replace(pattern, replacement)

pattern: string, regular expression

replacement: string, function

let originalString = "The quick brown fox jumps over the lazy dog.";

// Replace "fox" with "cat"

let newString = originalString.replace("fox", "cat");

console.log(newString); // "The quick brown cat jumps over the lazy dog."

It is important to note that replace DO NOT change( mutate  ) the original string, it simply returns a new string.

JavaScript replace() for complex pattern matching

You can add regular expressions ( RegExp ) as the pattern parameter for more complex matching and replacement.

let myString = "The quick brown fox jumped over the lazy dog.";
let newString = myString.replace(/the/gi, "a");
console.log(newString); // "a quick brown fox jumped over a lazy dog."

In the above example, the regular expression is “/the/gi”. 

The flag g stands for global( global search ). When you want to replace more than one time with the replacement string, you must you the g flag.

The flag i is for “case-insensitive”.  Thus, replace() method would match "the", "The", "tHe", "THE" , and any other variation of the word with different capitalization.

So, in simpler terms, the regular expression /the/gi tells the replace() method to find all occurrences of the word “the” in the string, regardless of whether the letters are uppercase or lowercase.

Therefore, in this case, replace() method would match the regular expression pattern and replace it with the letter “a”.

Replacement strings in replace()

In JavaScript when you use replace() method, you can utilize special replacement strings to insert certain values into the replacement string.

Some of these common values include,

  • $&: Inserts the matched substring.
  • $’: Inserts the portion of the string that follows the matched substring.
  • `$“: Inserts the portion of the string that precedes the matched substring.
  • $n or $nn: Inserts the nth or nth captured group, where n or nn is a number from 1 to 99.

Now, let’s take a look at the following example

Example 1:

const str = 'The quick brown fox jumps over the lazy dog.';
const result = str.replace(/quick/, '($&)');
console.log(result); // "The (quick) brown fox jumps over the lazy dog."

The pattern to match here is /quick/ and $& represents the matched substring: quick

The replacement string is ‘($&)’. Thus, the output is  “The (quick) brown fox jumps over the lazy dog.”

Example 2:

As mentioned before, $` inserts the portion of the string that precedes the matched substring.

const str = 'Jane and I are friends forever.';
const result = str. replace(/ and/, ", $`t, and ");

console.log(result); // "Jane, Janet, and  I are friends forever."

In the example above, I am matching / and/ ( the space and the word “and”). 

So, the matched string is “ and”, and the portion of the string that precedes the matched substring(“ and”) is “Jane”

$` represents the portion of the string that precedes the matched substring.

 Thus, " and" is replaced by ", Janet, and " producing the output: “Jane, Janet, and  I are friends forever.”

While you can use these special replacement strings in certain situations, using a function as a replacement can be more useful.  Next, deep dive into how you can use a replacer function as a parameter in the replace() method.

Using a replacement function in replace()

Not only can the replacement parameter take strings, but it can also take a function( replacer function ).

The replacer function as the following syntax:

function replacer(match, p1, p2, ..., pn, offset, string) {
 // function body
return replacement;
}

match: the matched substring

p1,p2,…pn: nth capturing group matched by the regular expression. The p parameters in the replacer function correspond to the capturing groups in the regular expression pattern provided as the first argument to the replace() method.

offset: index of the matched substring within the original string

string: the original input string

Now, we are going to see how you can use the replacer function as a parameter of the replace() method so that you will understand more about the above-mentioned parameters of the replacer function.

replace() method with replacer function: examples

Now, let’s see how to use the replacer function as a parameter in the replace() method.

Example 1:

const str = "Hello, world!";
const newStr = str.replace(/(\w+)/, (match, p1, offset, string) => {
  return "Goodbye";
});

console.log(newStr); // Output: "Goodbye, world!"

The function that is bolded and italicized in the above example is the replacer function.

In this case, it runs only once because the regular expression in the pattern parameter( the parameter of the replace() ) matches only once. 

Therefore the following value would be assigned during this run to each argument in the replacer function:

parametervaluecomment
match“Hello”the matched substring
p“Hello”the capturing group matched by the regular expression
offset0index of the matched substring within the original string
string“Hello World”The original input string

Now take look at the following example:

Example 2:

const str = "Hello World";
const newStr = str.replace(/(\w+) (\w+)/, (match, p1, p2) => {

//uncomment console statement below & examine the values
console.table({match,p1,p2 });
  return `${p1} Developers`
});

console.log( newStr)//output  “Hello Developers”

In this case, the regular expression (\w+) (\w+)/ has two capturing groups.

Thus, the value of p1 is “Hello” and the value of p2 is “World”. The regular expression matches a phrase with two words, which means the matched string(match parameter) is  “Hello World”.

Example 3:

const str = "apples, bananas, cherries";
const newStr = str.replace(/(\w+)/g, (match, p, offset, string) => {

//uncomment console statement below & examine the values
//console.table({match, p, offset, string});

  return "fruits";
});

console.log(newStr);

In the example above, the replacer function runs 3 times because the regular expression (/(\w+)/g is a global search to match every occurrence of a word in the input string.

replaceall()

The replaceAll()is a built-in method in the String object that replaces all occurrences of a specified string or regular expression with another string.

Here’s an example of how to use replaceall() method:

const str = 'Hello, World! How are you, World?';
const newStr = str.replaceAll('World', 'Universe');
console.log(newStr); // Output: "Hello, Universe! How are you, Universe?"

If you want to use replace instead of replaceall() , you must use g flag as below:

const str = 'Hello, World! How are you, World?';
const newStr = str.replace(/World/g, 'Universe');
console.log(newStr); // Output: "Hello, Universe! How are you, Universe?"

Last thoughts

The replace() method in JavaScript is used to replace a specified string or pattern with another string in a given string. It supports both basic string replacement and regular expressions, which offer more advanced options like the g flag for replacing all occurrences. The method also supports special replacement strings for dynamic replacements based on the matched pattern. The replaceAll() method is a newer addition that simplifies the process of replacing all occurrences of a string or pattern without using regular expressions.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top