JavaScript replace() and replaceAll()

Use replace() to replace the first string match (or matches selected by a regular expression). Use replaceAll() when you want every occurrence of a fixed string replaced.

const text = "PHP tutorial and PHP examples";
const updated = text.replace("PHP", "JavaScript");
console.log(updated); // JavaScript tutorial and PHP examples

replace() syntax Top ↑

string.replace(pattern, replacement)

The original string is not mutated.

Replace the first string match Top ↑

const text = "PHP tutorial and PHP examples";
console.log(text.replace("PHP", "JavaScript"));

Replace all occurrences Top ↑

const text = "PHP tutorial and PHP examples";
console.log(text.replaceAll("PHP", "JavaScript"));

replaceAll() is the clearest choice for every occurrence of a literal string.

Global replacement with a regular expression Top ↑

const text = "PHP tutorial and PHP examples";
console.log(text.replace(/PHP/g, "JavaScript"));

Case-insensitive replacement Top ↑

const text = "PHP tutorial and php examples";
console.log(text.replace(/php/gi, "JavaScript"));

The i flag ignores case and g selects all matches.

Replacement function Top ↑

const text = "Price: 20, tax: 5";
const result = text.replace(/\d+/g, value => String(Number(value) * 2));
console.log(result); // Price: 40, tax: 10

A replacer function can calculate replacement text dynamically.

Use capture groups in replacement text Top ↑

const name = "Mohapatra Subhendu";
console.log(name.replace(/(\w+) (\w+)/, "$2 $1"));

Common mistakes Top ↑

A plain string passed to replace() changes only the first occurrence. If you pass a regular expression to replaceAll(), it must use the global g flag. See also string searching.

Previous / String Reference Next related topic




Subscribe to our YouTube Channel here



plus2net.com










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer