문자열 매개 변수를 사용하고 그 안에있는 변수 참조 (해당되는 %로 지정)를 해당 변수 값으로 바꿔주는 함수를 만들고 싶습니다. 나는 eval() 함수의 위험에 대해 충분히 경고 받았지만 대안을 찾지 못했다. 나는이 코드가 얼마나 위험한 지 잘 모릅니다. 그것이 문제라면 어떤 접근 방식이 더 안전 할 것입니다. MH 수자 추천에 근거하여 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
}
, 나는이 작동합니다 생각하지만, 출력은 다음과 같습니다 :
%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
}
[템플릿 리터럴] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)을 사용하지 못하게하는 제약이 있습니까? –
이전에는 사용하지 않았고 구현 방법을 모르는 것 외에는 아무런 제약이 없습니다. – cycle4passion