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
string.replace(pattern, replacement)The original string is not mutated.
const text = "PHP tutorial and PHP examples";
console.log(text.replace("PHP", "JavaScript"));
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.
const text = "PHP tutorial and PHP examples";
console.log(text.replace(/PHP/g, "JavaScript"));
const text = "PHP tutorial and php examples";
console.log(text.replace(/php/gi, "JavaScript"));The i flag ignores case and g selects all matches.
const text = "Price: 20, tax: 5";
const result = text.replace(/\d+/g, value => String(Number(value) * 2));
console.log(result); // Price: 40, tax: 10A replacer function can calculate replacement text dynamically.
const name = "Mohapatra Subhendu";
console.log(name.replace(/(\w+) (\w+)/, "$2 $1"));
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
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.