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 ๐Ÿ˜„
  Tweet It

๐Ÿ•ต Search Results

๐Ÿ”Ž Searching...