Use .replace() or .replaceAll() to substitute text
const text = 'Hello World';
const replaced = text.replace('World', 'JavaScript');
console.log(replaced); // "Hello JavaScript"const message = 'The cat sat on the cat mat';
// Replace first occurrence
const single = message.replace('cat', 'dog');
console.log(single);
// Replace all occurrences
const all = message.replaceAll('cat', 'dog');
console.log(all);
// Using regex
const regex = message.replace(/cat/g, 'dog');
console.log(regex);
// With function
const capitalized = 'hello world'.replace(/\b\w/g, char =>
char.toUpperCase()
);
console.log(capitalized);const result = text.replace(/search/gi, 'replace');
// g = global, i = case insensitiveconst result = text.replace(/\d+/g, match =>
parseInt(match) * 2
);Avoid chaining multiple replaces
// DON'T DO THIS
var result = text.replace('a', 'x')
.replace('b', 'y')
.replace('c', 'z');✓ Works in all modern browsers (ES2021+ for replaceAll)