JavaScript变量替换问题

时间:2016-09-01 16:18:59

标签: javascript regex replace

我想替换一些字符串和变量,但我不知道如何制作它 - 我的代码如下:

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)

此脚本的输出是:

I was born in katin country kat

但重点是将kat替换为变量citycountry中的字符串。请注意,在var文本中,一些字符串有$个字符作为前缀 - 我想从变量中获取这些字符串(文本中的字符串将与变量名称相同但前缀为{{1 }})。

正确的输出应该是:

$

有人可以帮我吗?

4 个答案:

答案 0 :(得分:2)

你可以这样做:

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)

答案 1 :(得分:1)

您正在尝试构建的是一个“模板化”系统。如果你搜索它,你会发现很多东西。

这是一个非常简单的例子:

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

答案 2 :(得分:0)

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

如果您知道要替换的变量的顺序,这可能是您的解决方案。

答案 3 :(得分:0)

var city =“NEW YORK”

var country =“USA”

var text =“我出生在乡下的城市”

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

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

文件撰写(RES1);