string.replace 用变量替换

我们平常对字符串进行替换的时候

//一次替换
var str="Welcome Microsoft!"
str.replace(/Microsoft/,"W3School") //Welcome W3School!
//只会替换找到的第一个
//全局替换
var str="Welcome to MicrosoftMicrosoft! ";
str.replace(/Microsoft/g,"W3School") //Welcome to W3SchoolW3School!

项目里遇到需要传入一个变量,然后在替换

var text="Microsoft";
var str="Welcome to MicrosoftMicrosoft! ";
str.replace(new RegExp(text,'g'),"W3School");//Welcome to W3SchoolW3School!

封装

String.prototype.replaceAll=function(preVal,replaceVal){
    return this.replace(new RegExp(preVal,'g'),replaceVal);
}

遇到的问题

这样操作 直接 areaData = areaData.replace(new RegExp(i, "g"), formValue[i]);无效
需要转义一下

  for (i in formValue) {
       
        if (formValue[i] != '') {
            
            areaData = areaData.replace(new RegExp('\\'+i, "g"), formValue[i]);
            
            console.log(areaData);
        } else {
            formLength += i;
        }


    }
上一篇:云栖盛会中的人工智能


下一篇:Sticky footers