Back to Home
Strings

How to Replace Text in Strings

Use .replace() or .replaceAll() to substitute text

Quick Answer (2024 ES6+ Way)

javascript
const text = 'Hello World';
const replaced = text.replace('World', 'JavaScript');
console.log(replaced); // "Hello JavaScript"

Live Example

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);

Common Variations

Case Insensitive
javascript
const result = text.replace(/search/gi, 'replace');
// g = global, i = case insensitive
Dynamic Replacement
javascript
const result = text.replace(/\d+/g, match => 
  parseInt(match) * 2
);

❌ Don't Do This (Outdated Way)

Avoid chaining multiple replaces

javascript
// DON'T DO THIS
var result = text.replace('a', 'x')
                 .replace('b', 'y')
                 .replace('c', 'z');

Browser Support

Works in all modern browsers (ES2021+ for replaceAll)

#strings#replace#text