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

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

其他回答

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

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

在这个实例中,这可能不能满足您的确切需求,但我发现这是一种有用的方法,可以替换字符串中的多个参数,作为通用解决方案。它将替换参数的所有实例,无论它们被引用了多少次:

String.prototype.fmt = function (hash) {
        var string = this, key; for (key in hash) string = string.replace(new RegExp('\\{' + key + '\\}', 'gm'), hash[key]); return string
}

你可以这样调用它:

var person = '{title} {first} {last}'.fmt({ title: 'Agent', first: 'Jack', last: 'Bauer' });
// person = 'Agent Jack Bauer'

试试我的解决方案。请随意改进

函数multiReplace(字符串,regex,替换){ 返回str.replace(regex, function(x) { //检查替换键以防止错误,如果为false则返回原始值 return Object.keys(replace).includes(x) ?替换[x]: x; }); } var str = "我有一只猫,一只狗,和一只山羊。"; //(json)使用value替换键 Var替换= { “猫”:“狗”, “狗”:“山羊”, “山羊”:“猫”, } console.log(multiReplace(str, /Cat|dog|goat/g, replace))

const str = '感谢为Stack Overflow贡献一个答案!' Const substr = ['for', 'to'] 函数boldString(str, substr) { 让boldStr boldStr = str 字符串的子串。映射(e => { const strRegExp = new RegExp(e, 'g'); boldStr = boldStr。替换(strRegExp ' <强> $ {e} < / >强'); } ) 返回boldStr }

注意!

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

在这种情况下,有两种解决方法:(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] ) );

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