JS replaceAll 方法

13 min read

replaceAll() 方法返回一个新字符串,新字符串所有满足 pattern 的部分都已被replacement 替换。pattern可以是一个字符串或一个 RegExp, replacement可以是一个字符串或一个在每次匹配被调用的函数。

原始字符串保持不变。

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

console.log(p.replaceAll('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"


// global flag required when calling replaceAll with regex
const regex = /Dog/ig;
console.log(p.replaceAll(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"

结果:

> "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"

"The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"

.replaceAll will be available starting on Chrome 85. The current version is 83.

If you download Google Chrome Canary (which is on version 86), you'll be able to see that your code runs fine. Firefox is on version 78, and since .replaceAll has been available starting version 77, it works there too. It will work on current Safari as well. Microsoft Edge has it as unsupported.

You'll find supported browser versions at the bottom of the article in your question.