0

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
}

2
  • Do you have any constraints that prevent you from using template literals? Commented Oct 28, 2017 at 19:36
  • Other than never using them before and not quite knowing how to implement, I no contraints. Commented Oct 28, 2017 at 20:05

1 Answer 1

3

You can achieve this by using Template Literals.

In your case:

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

You just need to write your string like this: `My string`

And to concatenate a variable value, you write the variable like this: ${myVariable}

So, the final result would look like this:

const myVariable = 'awesome';
const finalResult = `My string is ${myVariable}` // My string is awesome
Sign up to request clarification or add additional context in comments.

1 Comment

code updated above, still not resolving like I would expect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.