用多个其他字符串替换多个字符串我试图用多个其他单词替换字符串中的多个单词。绳子是“我有一只猫,一只狗,一只山羊。”然而,这并不产生“我有一只狗,一只山羊,一只猫”,而是产生“我有一只猫,一只猫”。是否可以在JavaScript中同时将多个字符串替换为多个其他字符串,从而产生正确的结果?var str = "I have a cat, a dog, and a goat.";str = str.replace(/cat/gi, "dog");
str = str.replace(/dog/gi, "goat");str = str.replace(/goat/gi, "cat");
//this produces "I have a cat, a cat, and a cat"//but I wanted to produce the string "I have a dog, a goat, and a cat".
3 回答
繁华开满天机
TA贡献1816条经验 获得超4个赞
String.prototype.replaceAll = function(search, replacement) { var target = this; return target.replace(new RegExp(search, 'g'), replacement);};function replaceAll(str, map){ for(key in map){ str = str.replaceAll(key, map[key]); } return str;}//testing...var str = "bat, ball, cat";var map = { 'bat' : 'foo', 'ball' : 'boo', 'cat' : 'bar'};var new = replaceAll(str, map);//result: "foo, boo, bar"
添加回答
举报
0/150
提交
取消