0
我想创建一个函数,它接受一个字符串参数,并用它们对应的变量值替换其中的变量引用(用侧翼%指定)。我已经充分警告eval()函数的风险,但还没有找到替代方法。我不确定这个代码有多危险。如果这是一个问题,哪种方法会更安全。JS用变量内容替换字符串中的变量引用
以下是我有:
var a = 1;
var b = 2;
result = myFunction("a is %a%, b is %b%");
console.log(result); // return "a is 1, b is 2"
function myFunction(text) {
// escape needed chars in text for regex
text = text.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
var regExp = /%.+?%/g,
match;
while (match = regExp.exec(text)) {
rep = match[0].substr(1).slice(0, -1); // remove flanking %'s
text = text.replace(match[0], eval(rep));
}
return text
}
基于MH索萨的建议,我想这应该工作,但输出是:
%a% a
%b% b
a is a, b is b
var a = 1;
var b = 2;
result = myFunction("a is %a%, b is %b%");
console.log(result);
function myFunction(text) {
// escape neede chars in text for regex
text = text.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
var regExp = /%.+?%/g,
match;
while (match = regExp.exec(text)) {
var rep = match[0].substr(1).slice(0, -1); // remove flanking %'s
var rep = `${rep}`;
console.log(match[0], rep);
text = text.replace(match[0], rep);
}
return text
}
您是否有任何限制阻止您使用[template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)? –
除了以前从未使用过它们,并不知道如何实现,我没有任何限制。上面更新了代码 – cycle4passion