var insertProperty = function (string, propName, propValue) {
var propToReplace = "{{" + propName + "}}";
string = string
.replace(new RegExp(propToReplace, "g"), propValue);
return string;
}
此代码段是代码的一部分,从库中提取数据。我很难理解这一点,请帮忙。
答案 0 :(得分:3)
您的函数接受3个参数。假设:
string="This {{sample}} is just an example {{sample}}"
propName="sample"
propValue="code"
所以propToReplace={{sample}}
string = string.replace(new RegExp(propToReplace, "g"), propValue)
是一个正则表达式,它将{{sample}}
替换为code
,新的字符串将变为
This code is just an example code
"g"
中的第二个参数new RegExp()
表示全局标志,这意味着它将用字符串参数中出现的{{sample}}
替换code
的所有出现。
答案 1 :(得分:1)
insertProperty
-是一个匿名函数,它获得3个参数:string,propName,propValue。它将替换值为{{propName}}
的新字符串返回到propValue。
如果此函数获取的string
等于{{hello}} world
,propName等于hello
并且propValue等于bye
,则执行函数insertProperty后的结果等于- bye world