liveBook · Manning

Replace method

As explained in Secrets of the JavaScript Ninja, Second Edition

A JavaScript String method that returns a new string with matched text replaced by specified text or text produced by a callback.

String.replace() substitutes matched text. Give it a regular expression to match a pattern rather than a fixed string; a global regex replaces every match. section 10.5

A replacement callback lets each match produce its own replacement:

  • It receives the full match, captures, match index, and source string; its return value becomes the replacement. section 10.5
  • For example, a callback can uppercase the letter after each dash to convert a dashed name to camel case. section 10.5
Listing 10.9. Converting a dashed string to camel case
 function upper(all,letter) { return letter.toUpperCase(); }        #A
 assert("border-bottom-width".replace(/-(\w)/g,upper)               #B
       === "borderBottomWidth",
      "Camel cased a hyphenated string.");

A callback-based example converts a hyphenated string to camel case. section 10.5

Listing 10.10. A technique for compressing a query string
function compress(source) {
  const keys = {};                                      #A
  source.replace(
    /([^=&]+)=([^&]*)/g,
    function(full, key, value) {                        #B
      keys[key] =
        (keys[key] ? keys[key] + "," : "") + value;
      return "";
    }
  );
  const result = [];                                    #C
  for (let key in keys) {                               #C
    result.push(key + "=" + keys[key]);                 #C
  }                                                     #C
  return result.join("&");                              #D
}

assert(compress("foo=1&foo=2&blah=a&blah=b&foo=3") ===
       "foo=1,2,3&blah=a,b",
       "Compression is OK!");

This example uses a global regex and callback to collect repeated query-string values. section 10.5

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains global matching and callback arguments with worked examples, without detailing implementation internals.
Examples
Demonstrates uppercase substitution, camel-case conversion, and query-string compression.
What you can do after
Apply String.replace() with regexes and callbacks to transform matched text or process repeated matches.
How it connects
Connects regular expressions with capture groups and global matching.

Also explained in

Compare how 6 books explain replace method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.