0

I am saving string into mongoDB with preset variable as

'Current time is ${time}'

After that I am retrieving somewhere else this string and would like to assign value to time

It would look something like this

const time = '15:50'    
const response = result //saves string retreived from mongo

res.json({
   response: response
})

But that returns 'Current time is ${time}' instead of 'Current time is 15:50'

I am aware that the string should be in `` instead of single quotes for variable to work, not sure though how to implement that as output from mongo

Anyone could point me to correct direction?

4
  • 2
    You have to use backticks instead of simple quotes ` instead of ' for that string : `Current time is ${time}` Commented Nov 18, 2017 at 18:36
  • it is retrieved from mongo automatically as string in single quotes, I know it must be in backticks I was wondering if there is any way to transform it. Commented Nov 18, 2017 at 18:38
  • You could also use String.replace. Commented Nov 18, 2017 at 18:44
  • Related: stackoverflow.com/questions/29182244/… Commented Nov 18, 2017 at 19:13

3 Answers 3

2

An alternative is to pass the string and parameters to a function and reduce over the parameters object:

var str = 'Current time is ${time}';
var params = { time: '13:30' };

function merge(str, params) {
  return Object.keys(params).reduce((out, key) => {
    return str.replace(`\${${key}}`, params[key]);
  }, '');
}

console.log(merge(str, params));

Sign up to request clarification or add additional context in comments.

Comments

1

And this is an example of interpolation magic, as mentioned in other answer ;) Note, than even without the evil() ;)

var time = '15:50' 
var response = 'Current time is ${time}'

var converted = (_=>(new Function(`return\`${response}\`;`))())()

console.log(converted)

Comments

1

Interpolation is not performed on a string variable that happens to contain a template literal placeholder. In order for interpolation to happen, you must have a literal string in the code, enclosed in back ticks with a placeholder:

let time = '15:50';
let message = `Current time is ${time}`
console.log(message); // "Current time is 15:50"

If you must store strings in your database, you'll have to come up with your own mechanism for interpolating your placeholders.

Comments

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.