I want create a function which takes a string parameter and replaces variable references within it (designated with flanking %'s) with their corresponding variable values. I have been sufficiently warned about risk of eval() function, but haven't found an alternative. I am not sure how risky this code is. If it is a problem, what approach would be more secure.
Here is what I have:
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
}
Based upon MH Souza recommendation, I figured this should work, but output is:
%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
}