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?

Rob Johansen
  • 5,076
  • 10
  • 40
  • 72
iamwtk
  • 1,031
  • 3
  • 13
  • 24
  • 2
    You have to use backticks instead of simple quotes `\`` instead of `'` for that string : `\`Current time is ${time}\`` – caisah Nov 18 '17 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. – iamwtk Nov 18 '17 at 18:38
  • You could also use `String.replace`. – caisah Nov 18 '17 at 18:44
  • Related: https://stackoverflow.com/questions/29182244/convert-a-string-to-a-template-string – Maluen Nov 18 '17 at 19:13

3 Answers3

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));
Andy
  • 61,948
  • 13
  • 68
  • 95
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)
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.

Rob Johansen
  • 5,076
  • 10
  • 40
  • 72