我试图用多个其他单词替换字符串中的多个单词。字符串是“我有一只猫,一只狗和一只山羊。”

然而,这并不会产生“我有一只狗、一只山羊和一只猫”,而是产生“我有一只猫、一只猫和一只猫”。是否有可能在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".

当前回答

String.prototype.replaceSome = function() {
    var replaceWith = Array.prototype.pop.apply(arguments),
        i = 0,
        r = this,
        l = arguments.length;
    for (;i<l;i++) {
        r = r.replace(arguments[i],replaceWith);
    }
    return r;
}

/* 字符串的replaceSome方法 它需要尽可能多的参数,然后替换所有参数 我们指定的最后一个参数 2013年版权保存:Max Ahmed 这是一个例子:

var string = "[hello i want to 'replace x' with eat]";
var replaced = string.replaceSome("]","[","'replace x' with","");
document.write(string + "<br>" + replaced); // returns hello i want to eat (without brackets)

*/

jsFiddle: http://jsfiddle.net/CPj89/

其他回答

具体的解决方案

您可以使用一个函数来替换每一个。

var str = "I have a cat, a dog, and a goat.";
var mapObj = {
   cat:"dog",
   dog:"goat",
   goat:"cat"
};
str = str.replace(/cat|dog|goat/gi, function(matched){
  return mapObj[matched];
});

jsfiddle例子

概括它

如果您想动态地维护正则表达式,并且只是将未来的交换添加到映射中,您可以这样做

new RegExp(Object.keys(mapObj).join("|"),"gi"); 

生成正则表达式。就像这样

var mapObj = {cat:"dog",dog:"goat",goat:"cat"};

var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
str = str.replace(re, function(matched){
  return mapObj[matched];
});

要添加或更改任何替换,您只需编辑地图。

摆弄动态正则表达式

可重复使用

如果你想让它成为一般形式你可以把它变成这样一个函数

function replaceAll(str,mapObj){
    var re = new RegExp(Object.keys(mapObj).join("|"),"gi");

    return str.replace(re, function(matched){
        return mapObj[matched.toLowerCase()];
    });
}

然后你可以把str和你想要的替换的映射传递给函数它会返回转换后的字符串。

摆弄函数

确保对象。key适用于旧的浏览器,添加一个填充,例如从MDN或Es5。

所有的解决方案都很好,除了应用于闭包的编程语言(如Coda, Excel,电子表格的REGEXREPLACE)。

我下面的两个原始解决方案只使用1个连接和1个正则表达式。

方法#1:查找替换值

其思想是,如果替换值不在字符串中,则附加替换值。然后,使用一个regex,我们执行所有需要的替换:

var str = "我有一只猫,一只狗,和一只山羊。"; STR = (STR +"||||猫,狗,山羊").replace( /猫(? = [\ s \ s] *(狗))|狗(? = [\ s \ s] *(山羊))|山羊(? = [\ s \ s] *(猫 ))|\|\|\|\|.* $ / gi, " $ 1 $ 2 $ 3”); document.body.innerHTML = str;

解释:

cat(?=[\s\S]*(dog)) means that we look for "cat". If it matches, then a forward lookup will capture "dog" as group 1, and "" otherwise. Same for "dog" that would capture "goat" as group 2, and "goat" that would capture "cat" as group 3. We replace with "$1$2$3" (the concatenation of all three groups), which will always be either "dog", "cat" or "goat" for one of the above cases If we manually appended replacements to the string like str+"||||cat,dog,goat", we remove them by also matching \|\|\|\|.*$, in which case the replacement "$1$2$3" will evaluate to "", the empty string.

方法#2:查找替换对

方法#1的一个问题是它一次不能超过9个替换,这是反向传播组的最大数量。 方法#2声明不只是附加替换值,而是直接替换:

var str = "我有一只猫,一只狗,和一只山羊。"; str = (str + " | | | |,猫= >狗,狗= >山羊,山羊= >猫”).replace ( / (\ b \ w + \ b) (? = [\ s \ s] * \ 1 =>([^,]*))|\|\|\|\|.* $ / gi, " $ 2 "); document.body.innerHTML = str;

解释:

(str+"||||,cat=>dog,dog=>goat,goat=>cat") is how we append a replacement map to the end of the string. (\b\w+\b) states to "capture any word", that could be replaced by "(cat|dog|goat) or anything else. (?=[\s\S]*...) is a forward lookup that will typically go to the end of the document until after the replacement map. ,\1=> means "you should find the matched word between a comma and a right arrow" ([^,]*) means "match anything after this arrow until the next comma or the end of the doc" |\|\|\|\|.*$ is how we remove the replacement map.

注意!

如果您正在使用动态提供的映射,这里的解决方案都不够!

在这种情况下,有两种解决方法:(1)使用分割连接技术,(2)使用正则表达式和特殊字符转义技术。

这是一个分割连接技术,它比另一个快得多(至少快50%):

var str = "I have {abc} a c|at, a d(og, and a g[oat] {1} {7} {11." var mapObj = { 'c|at': "d(og", 'd(og': "g[oat", 'g[oat]': "c|at", }; var entries = Object.entries(mapObj); console.log( entries .reduce( // Replace all the occurrences of the keys in the text into an index placholder using split-join (_str, [key], i) => _str.split(key).join(`{${i}}`), // Manipulate all exisitng index placeholder -like formats, in order to prevent confusion str.replace(/\{(?=\d+\})/g, '{-') ) // Replace all index placeholders to the desired replacement values .replace(/\{(\d+)\}/g, (_,i) => entries[i][1]) // Undo the manipulation of index placeholder -like formats .replace(/\{-(?=\d+\})/g, '{') );

这一个,是Regex特殊字符转义技术,它也有用,但慢得多:

var str = "I have a c|at, a d(og, and a g[oat]." var mapObj = { 'c|at': "d(og", 'd(og': "g[oat", 'g[oat]': "c|at", }; console.log( str.replace( new RegExp( // Convert the object to array of keys Object.keys(mapObj) // Escape any special characters in the search key .map(key => key.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')) // Create the Regex pattern .join('|'), // Additional flags can be used. Like `i` - case-insensitive search 'g' ), // For each key found, replace with the appropriate value match => mapObj[match] ) );

后者的优点是,它也可以用于不区分大小写的搜索。

我写了这个npm包stringinject https://www.npmjs.com/package/stringinject,它允许你做以下事情

var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);

这将替换{0}和{1}与数组项,并返回以下字符串

"this is a test string for stringInject"

或者你可以像这样用对象键和值替换占位符:

var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });

"My username is tjcafferkey on Github" 

可以使用分隔符查找和替换字符串。

Var obj = { “firstname”:“约翰”, “姓”:“母鹿” } var文本= "你好{firstname},你的名字是{firstname}和姓氏是{lastname}" console.log (mutliStringReplace (obj、文本)) 函数mutliStringReplace(对象,字符串){ Var val =字符串 var entries = object .entries(object); entries.forEach ((para) = > { Var find = '{' + para[0] + '}' var regExp = new regExp (find,'g') val = val.replace(regExp, para[1]) }) 返回val; }