Javascript variables appended in a string not getting replaced with it's original value

The string ''+notify_name+' likes your post.' is coming from the database. We are storing this static string in the database.

variable ntfnFound[0].body contains this string that we fetched from the database.

var notify_name = 'tintu';

console.log(ntfnFound[0].body);   /* ''+notify_name+' likes your post.' */

var body = ntfnFound[0].body;

console.log(body);   /* ''+notify_name+' likes your post.' */

console.log(''+notify_name+' likes your post.');   /*tintu likes your post*/

My question is,

In the above code why not 'console.log(body);' displays 'tintu likes your post' ??

or

Why +notify_name+ is not getting replaced ??

Also is there any solution for converting the string in 'var body' to 'tintu likes your post' ??

IN the following code works,

console.log(''+notify_name+' likes your post.');   /*tintu likes your post*/

Upvotes: 0

Views: 123

Answers (2)

null
null

Reputation: 55

My first guess would be: You saved the STRING in your DB, when pulling it out, it is still a String, so must likely the ' and + are escaped: \' and \+.

What you are trying to accomplish is to save a String in your DB where you later want to insert the value of your variable.

My approach would be: saving something like "{0} likes your post" and then use some kind of printf function on it.

have a look at : JavaScript equivalent to printf/string.format

Upvotes: 1

MBaas
MBaas

Reputation: 7530

There are no automagic replacements in JS - you'll have to it yourself with body.replace("+notify_name+",notify_name);.

The reason it worked in the log is. because JS did what you told it to do: '' is an empty string, then you catenated the name and the text 'likes your post'.

Upvotes: 0

Related Questions