由于 JavaScript 的 replace 只能替换一次, 因此另外编写一个能现替换全部匹配内容方法, 代码如下:
- /*
- 把 content 中所有的 searchValue 替换为 replaceValue
- */
- function replaceAll(content,searchValue,replaceValue){
- while (content.indexOf(searchValue)>-1) {
- content = content.replace(searchValue,replaceValue);
- }
- return content;
- }
为什么不使用正侧表达式来替换?
因为实际操作中发现 searchValue 的内容太大的时候使用正侧表达式替换会出错
我的场景是把 html 页面 img 中的 base64 xxx1,base64 xxx2 图片内容替换为 [image1][image2] 这样的占位符时, 如果使用正则表达式就出错
附上一般情况下使用正侧表达式的替换方法
content.replace(new RegExp(searchValue,'g'),replaceValue)
来源: https://www.cnblogs.com/anyjs/p/12297431.html