liveBook · Manning

Replace method

As explained in Secrets of the JavaScript Ninja, Third Edition

String.prototype.replace is a JavaScript String method that returns a new string with matched text replaced by specified text or the result of a replacement function.

String.prototype.replace creates a new string with matching text replaced; it does not modify the original string. The replacement can be literal text or a regular expression. section 12.5

const warrior = "Kung-Fu Panda";
warrior.replace("Kung-Fu", "Jiu-Jitsu"); // "Jiu-Jitsu Panda" 

Replace an exact substring with another string. section 12.5

const scaryCreatureRegex = /rat|snake|dragon/;
const message = "Hiss, I'm a snake!";
message.replace(scaryCreatureRegex, "puppy"); // "Hiss, I'm a puppy!"

Pass a regular expression to replace text matching a pattern. section 12.5

A replacer function can transform each match. It receives the full match, captured groups, the match’s index, and the original string. A global regex invokes it for every match; without the global flag, matching stops after one. section 12.5 section 12.7

Listing 12.8 Using a replacer function to transform a string
const kebabCaseRegex = /-([a-z])/g; #A
const technique = "shadow-clone-jutsu";
const camelCase = technique.replace( #B
  kebabCaseRegex, #B
  (_, letter: string) => letter.toUpperCase(), #B
); #B

console.assert(
  camelCase === "shadowCloneJutsu",
  "The kebab-case string becomes 'shadowCloneJutsu'",
);

Use a capture and callback to convert kebab-case text to camelCase; the TypeScript example annotates the captured letter. section 12.5

The example pattern handles a hyphen followed by a lowercase letter, but an edge case is left for a more robust pattern using lookbehind. section 12.5

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains replacement callbacks, captures, and global matching, while deferring a robust pattern for the noted edge case.
Examples
Demonstrates literal and regex substitutions, plus converting a kebab-case string to camelCase.
What you can do after
Apply String.prototype.replace to substitute literal text, replace regex matches, or transform captures with a callback.
How it connects
Connects regular expressions, capture groups, global matching, and lookbehind.

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, Third Edition. The section links point to the parts of the book it draws on.