JS: String.prototype.replace

By Xah Lee. Date: . Last updated: .

String.prototoype.replace has 2 different behavior, depending on if the first argument is string or regex object.

str.replace(str1,str2)

str.replace(regex_obj,replace_str_or_func)

[see JS: RegExp Syntax]

When using regex, the following dollar sign sequence have special meaning in the replace string.

  1. $nnth grouped match. (n is a positive integer less than 100)
  2. $& → the matched string.
  3. $` → the string before the matched string.
  4. $' → the string after the matched string.
  5. $$ → literal dollar sign character.

Replace All

To replace all occurrences, use regex with the global flag g.

// replace all
const x1 = "no no no";
const x2 = x1.replace(/no/g, "yes");
console.log ( x2 === "yes yes yes" ); // true

Non-RegExp Example

// example of literal replace

const xx = "a.b.c";

console.log( xx.replace(".", "9") === "a9b.c" ); // true
// Only first occurrence is replaced
// first arg is treated as string, not regex

// original string is not changed
console.log( xx === "a.b.c" ); // true

If not found, returns the original string:

// if not found, returns the original string
const xx = "abc";
console.log( xx.replace("e", "3") === "abc" ); // true

RegExp Example

Basic example:

// example of RegExp replace
const xx = "joe@example.com";
console.log( xx.replace(/@.+\.com/, "") === "joe" ); // true

Example of “replace” method with captured group:

// example of RegExp replace

// add alt attribute to a HTML image tag.

const x1 = '<img src="cat.jpg">';

const x2 = x1.replace(/<img src="([-_\w]+)\.jpg">/, '<img src="$1.jpg" alt="$1">');

console.log(x2); // prints <img src="cat.jpg" alt="cat">

Example using “replace” method with a function as second argument.

// example of RegExp replace, using function as replacement

// add a alt attribute to a HTML image tag, but convert any underscore to space
// for example, we want
// <img src="my_cat.jpg">
// to become
// <img src="my_cat.jpg" alt="my cat">

const ff = ((whole, group1) => (`<img src="${group1}.jpg" alt="${group1.replace(/_/g, ' ')}">`));

const x1 = '<img src="big_black_cat.jpg">';

const x2 = x1.replace(/<img src="([-_\w]+)\.jpg">/, ff);

console.log ( x2 === '<img src="big_black_cat.jpg" alt="big black cat">' ); // true

JS RegExp

  1. RegExp Tutorial
  2. RegExp Syntax
  3. Regex Find/Replace

JS String

  1. String Overview
  2. Template String
  3. Char, Code Unit, Codepoint
  4. String Escape Sequence
  5. Unicode Escape Sequence
Liket it? I spend 2 years writing this tutorial. Help me spread it. Tell your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog