如何在Javascript中对多个变量执行相同的替换

时间:2018-12-10 01:18:16

标签: javascript string replace

我想对多个变量进行相同的替换。这是一个有效的示例,但是我必须为每个变量编写replace语句。我可以将replace函数设为每个变量,然后为每个变量调用该函数,但是我想知道是否有一种更有效的方法可以在一行中完成,例如string1,string2,string3(replace...

<script>
string1="I like dogs, dogs are fun";
string2="The red dog and the brown dog died";
string3="The dog likes to swim in the ocean";
string1=string1.replace(/dog/g,'cat');
string2=string2.replace(/dog/g,'cat');
string3=string3.replace(/dog/g,'cat');

alert(string1+"\n"+string2+"\n"+string3);
</script>

1 个答案:

答案 0 :(得分:1)

使用数组代替,.map到新数组,对每个数组执行replace操作:

const dogToCat = str => str.replace(/dog/g,'cat');
const strings = [
  "I like dogs, dogs are fun",
  "The red dog and the brown dog died",
  "The dog likes to swim in the ocean"
];
console.log(
  strings
    .map(dogToCat)
    .join('\n')
);

如果您必须使用独立变量并重新分配给它们,则可以对结果进行重构,尽管它很丑陋,而且可能不是一个好主意({const是首选,如果可能):

const dogToCat = str => str.replace(/dog/g, 'cat');
let string1 = "I like dogs, dogs are fun";
let string2 = "The red dog and the brown dog died";
let string3 = "The dog likes to swim in the ocean";

([string1, string2, string3] = [string1, string2, string3].map(dogToCat));
console.log(string1 + "\n" + string2 + "\n" + string3);