JS: String.prototype.replace

By Xah Lee. Date: . Last updated: .

The method String.prototoype.replace has 2 forms. The first arg can be a literal string, or a RegExp object. They have different behavior.

str.replace(find_str,replace_str)

  1. The first occurrence of find_str in string str is replaced by string replace_str.
  2. No regex is used.
  3. Returns a new string.
  4. If no match, the original string is returned.
  5. str is not changed.

str.replace(regex_obj,replace_str_or_func)

  1. Return a new string.
  2. The replace_str_or_func can be a string or function.
  3. If string, {$1, $2, …} refers to captured group.
  4. If function, it'll receive args: {matched substring, capture group 1, capture group 2, …}. If no match, the original string is returned.
  5. str is not changed.

Non-RegExp Example

// example of literal replace

const xx = "aaa";

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

console.log( xx.replace("a+", "9") === "aaa" ); // true
// No change, because no match.
// first arg is treated as string, not regex

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

Only first occurrence is replaced:

// only the first occurrence is replaced

const xx = "aaa";

console.log(
    xx.replace("a", "b") // returns baa
);

If not found, returns the original string:

// if not found, returns the original string

const xx = "abc.xyz";

console.log(
    xx.replace("e", "3") // returns abc.xyz. because not found
);

RegExp Example

Basic example:

// example of RegExp replace

const xx = "jane@example.com";

console.log(
    xx.replace(/@.+\.com/, "")
); // prints "jane"

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">

function underscore_to_space(whole, capture1) {
    return '<img src="' + capture1 + '.jpg"' + ' alt="' + capture1.replace("_", " ") + '">';
};

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

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

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

Reference

ECMAScript® 2016 Language Specification#sec-string.prototype.replace

RegExp Topic

  1. JS: RegExp Tutorial
  2. JS: RegExp Syntax
  3. JS: Regex Find/Replace
  4. JS: RegExp Object
  5. JS: RegExp Constructor
  6. JS: RegExp.prototype

String Topic

  1. JS: String Overview
  2. JS: Template String
  3. JS: String Object
  4. JS: String.prototype
  5. JS: String Code Unit vs Code Point
  6. JS: String Escape Sequence
  7. JS: Unicode Escape Sequence
  8. JS: Source Code Encoding
  9. JS: Allowed Characters in Identifier
  10. JS: Convert String to Number
  11. JS: Encode URL, Escape String
  12. JS: Format Number
  13. JS: JSON
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

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