How do you replace all occurrences of a substring in JavaScript using replaceAll() or regex? | A1Lab@FahadM to JavaScriptEnglish •
edit-2
12 days ago

How do you replace all occurrences of a substring in JavaScript using replaceAll() or regex?

message-square
0

'Use the modern String.prototype.replaceAll() method for literal substring replacements, or replace(/pattern/gi, replacement) when you need case-insensitive or pattern-based matching.

Using .replaceAll() (Recommended for Exact Matches)

const text = "JS is fast. JS is everywhere.";

// Replaces every occurrence of "JS" safely without regex escaping
const updated = text.replaceAll("JS", "JavaScript");
console.log(updated); // "JavaScript is fast. JavaScript is everywhere."

Using Global Regex /g (For Case-Insensitive Matches)

const mixed = "js is fast. JS is everywhere.";
const updatedAll = mixed.replace(/js/gi, "JavaScript"); '