super-user super-user - 18 days ago 5
Javascript Question

Javascript - Replacing a part of string within special characters

I have 2 javascript variables that has values:

var Name = 'John';
var Age = '14';


and another string variable that looks like this:

var message = 'I am **Name** and my age is **Age**';


How can I inject the value of
Name
and
Age
variables into the
message
string to replace the
**Name**
and
**Age**
with values 'John' and '14'?

var newmessage = 'I am John and my age is 14';


Is there a javascript function I can use to perform this?

Answer

Use String#replace method and get variable from window object (only works when the variable is defined in the global context other ways you need to use eval() method which I don't prefer to use.).

var Name = 'John';
var Age = '14';
var message = 'I am **Name** and my age is **Age**';
var newmessage = message.replace(/\*\*([\w\d]+)\*\*/g, function(m, m1) {
  return window[m1];
});

console.log(newmessage)


Or use an object instead of variables for storing the value so you can get value easily even it's not defined in global context.

var obj = {
  Name: 'John',
  Age: '14'
};
var message = 'I am **Name** and my age is **Age**';
var newmessage = message.replace(/\*\*([\w\d]+)\*\*/g, function(m, m1) {
  return obj[m1];
});

console.log(newmessage)