javascript - 如何对 Javascript 中的多个变量进行相同的替换

标签 javascript string 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>

最佳答案

改用数组,并 .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')
);

如果您必须使用独立变量并重新分配给它们,那么您可以解构结果,尽管它很难看并且可能不是一个好主意(consts如果可能的话,最好):

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

关于javascript - 如何对 Javascript 中的多个变量进行相同的替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53698360/

相关文章:

javascript - 使用 jQuery 滚动一个 div

javascript - Firefox 无法识别返回的 json 数组,chrome 可以

java - 对大文本进行子串的更好方法是什么?

c# - Convert.ToDouble 和 double.Parse 与 InvariantCulture 的区别

java - 交换字符串中的两个字母

javascript - 下载 js 和 css 时显示加载信息

javascript - javascript 中按钮点击必须按顺序

bash - AWK 将 NULL 列值替换为前一行的列值(续)

Javascript 替换不匹配的字符串?

java - String#replace 在我的方法中不起作用