artielegancko artielegancko - 3 months ago 16
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)) {
variable.push(c[1]);
}

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

console.log(text)


Output from this script is:

I was born in katin country kat


But the point is to replace the
kat
with the strings from variable
city
and
country
. 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

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]);

console.log(newString);

Comments