SyntaxStudy
Sign Up
Home JavaScript Reference replace() / replaceAll()

replace() / replaceAll()

method ES2021

replace() replaces the first match; replaceAll() replaces all occurrences.

Syntax

string.replace(pattern, replacement)

Example

javascript
const text = 'Hello World, Hello JS';

text.replace('Hello', 'Hi');      // 'Hi World, Hello JS'
text.replaceAll('Hello', 'Hi');   // 'Hi World, Hi JS'

// With regex
text.replace(/Hello/g, 'Hi');     // 'Hi World, Hi JS'

// Replace function
const str = 'hello world';
str.replace(/\b\w/g, c => c.toUpperCase());
// 'Hello World' (capitalize each word)