2017-10-28 1 views
0

문자열 매개 변수를 사용하고 그 안에있는 변수 참조 (해당되는 %로 지정)를 해당 변수 값으로 바꿔주는 함수를 만들고 싶습니다. 나는 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 
 
}

+0

[템플릿 리터럴] (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