artielegancko
artielegancko

Reputation: 21

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?

Upvotes: 0

Views: 103

Answers (4)

SUNITHA K
SUNITHA K

Reputation: 148

var city = "NEW YORK"

var country = "USA"

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

var res = text.replace(/city/gi, city);

var res1 = res.replace(/country/gi, country);

document.write(res1);

Upvotes: 0

user663031
user663031

Reputation:

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

Upvotes: 1

CoverFire
CoverFire

Reputation: 1

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

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

var replaceArray = [city,country]; //create an array with your variables

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("$"+variable[n], replaceArray[n]);
}

console.log(text);

If you know the order of the variables you want to replace, this could be your solution.

Upvotes: 0

Huntro
Huntro

Reputation: 322

You can just do it like this:

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

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

text = text.replace("$city", city);
text = text.replace("$country", country);

console.log(text)

Upvotes: 2

Related Questions