whatstheoutput_

#44: replace() vs replaceAll()

Topic: strings · Difficulty: ★★

const s = 'ababab';
console.log(s.replace('a', 'X'));
console.log(s.replaceAll('a', 'X'));

Output

Xbabab
XbXbXb

Why

When given a plain string (not a global regex) as the pattern, String.prototype.replace() only ever replaces the FIRST match it finds and stops — that's why only the leading 'a' in 'ababab' turns into 'X'. replaceAll(), added later to the language specifically to fix this ergonomic gap, replaces every non-overlapping match of the given string, turning all three 'a' characters into 'X'. Before replaceAll existed, replacing every occurrence with a plain string required a regex with the /g flag instead, since replace() with a string pattern can never behave globally.

More strings puzzles

Play today's puzzle →