artielegancko artielegancko - 1 year ago 79
Javascript Question

JavaScript variable replace issue

I want to replace some strings and variables but I don`t know how to make it - my code is below:

var text = "I was born in $city in country $country "

var city = "New YORK"
var country = "USA"

var regex_variable = /\$\s*(.*?)\s/g;
var variable =[];

while (c = regex_variable.exec(text)) {

for (n=0;n<variable.length;n++){
text = text.replace(regex_variable, "kat");


Output from this script is:

I was born in katin country kat

But the point is to replace the
with the strings from variable
. Please note that in the var text some strings has got
character as a prefix - this strings I want to take from the variables (strings in the text will be the same as a names of variables but with prefix

The correct output should be:

I was born in New YORK in country USA

Anyone could help me with it?

Answer Source

What you're trying to build is a little "templating" system. If you search for that, you will find lots of things.

Here's a real simple example:

var city = "New YORK";
var country = "USA";
var interpolations = {city, country};
var text = "I was born in $city in country $country";

var newString = text.replace(/\$(\w+)/g, (match, val) => interpolations[val]);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download