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





