JavaScript: 文本替换, 替换全部, 正则替换文本, How to replace all occurrences of a string in JavaScript?

一次 replace只能替换一个,例如:

var str = 'test test test test'
console.log(str.replace('test', 'tester'))

通过正则可以一下替换全部:

someString = 'the cat looks like a cat';
anotherString = someString.replace(/cat/g, 'dog');
// anotherString now contains "the dog looks like a dog"

 

JavaScript: 文本替换, 替换全部, 正则替换文本, How to replace all occurrences of a string in JavaScript?
JavaScript: 文本替换, 替换全部, 正则替换文本, How to replace all occurrences of a string in JavaScript?

 

更多参考:http://www.tizag.com/javascriptT/javascript-string-replace.php

 

本文:JavaScript: 文本替换, 替换全部, 正则替换文本, How to replace all occurrences of a string in JavaScript?