2017-10-28 181 views
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 
 
}

+0

您是否有任何限制阻止您使用[template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)? –

+0

除了以前从未使用过它们,并不知道如何实现,我没有任何限制。上面更新了代码 – cycle4passion

回答

3

你可以通过使用Template Literals来实现。

你的情况:

const a = 1; 
const b = 2; 
const result = `a is ${a}, b is ${b}`; // a is 1, b is 2 

你只需要编写你的字符串是这样的: `我string`

且级联一个变量的值,你写这样的变量: $ {} MYVARIABLE

所以,最后的结果是这样的:

const myVariable = 'awesome'; 
const finalResult = `My string is ${myVariable}` // My string is awesome 
+0

,仍然没有像我期望的那样解决。 – cycle4passion