JavaScript String Replace

Replacing text in a string is a very common operation, and thank’s to the replace method available on the String prototype, it’s very easy to do.

The simplest use-case is to provide a string that will act as a substring to match and a string replacement as the second argument:

let myStr = 'My little Alligator 🐊';

console.log(myStr.replace('Alligator', 'gator')); // My little gator 🐊

Replace operations can also be chained:

let myStr = 'My little Alligator 🐊';

myStr = myStr
  .replace('Alligator', 'gator')
  .replace('My', 'Your')
  .replace('gator 🐊', 'unicorn πŸ¦„');

console.log(myStr); // Your little unicorn πŸ¦„

Given that strings are immutable in JavaScript, replace returns a new string.

You can use $& in the replacement string to include the match:

let myStr = 'My little Alligator 🐊';

console.log(myStr.replace('gator', '-$&-$&'));
// My little Alli-gator-gator 🐊
  • Use $` to insert the part of the string that’s before the match.
  • Use $’ to insert the part of the string that’s after the match.
  • Use $n, to insert the nth match.

RegExp Match

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

let myStr = 'Does my text make sense?';

myStr = myStr.replace(/e/g, 'a');

console.log(myStr); // Doas my taxt maka sansa?

In the above example, we used the global (g) flag on the regular expression literal to match all occurrences. The i flag is also often useful for a case-insensitive match.

Here’s an example where we iterate over an array of strings and replace fractions followed by a unit (tsp or tbsp):

let ingredients = ['1/4 tsp honey', '1/2 tbsp coconut oil', '1/8 tsp cocoa'];

ingredients = => {
  return ingredient.replace(/(\d\/\d) (tsp|tbsp)/, 'Lots of');

// ["Lots of honey", "Lots of coconut oil", "Lots of cocoa"]

Function as 2nd Argument

The second argument can also be a function, known as the replacer function. The return value of the function will be the value used for replacement. Here’s a simple example:

let myStr = '49.5 Red Balloons';

myStr = myStr.replace(/\d+\.\d+/, (match) => {
  return +match * 2; // 49.5 * 2

console.log(myStr); // 99 Red Balloons

The first argument to the replacer function is the full match itself. You can also use additional arguments (often called p1, p2,…) to get the nth captured group from the match. This final example is a little silly, but it illustrates the functionality:

let myStr = 'My friendly Alligator';

myStr = myStr.replace(/(\w+) (\w+) (\w+)/, function (match, p1, p2, p3) {
  return `${p1}/${p2}/${p3} πŸ˜„`;

console.log(myStr); // My/friendly/Alligator πŸ˜„
✖ Clear

πŸ•΅ Search Results

πŸ”Ž Searching...