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

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

具体的解决方案

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

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。


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

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'

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/


我扩展了一下@本麦考密克斯。他的工作规则字符串,但不如果我转义字符或通配符。我是这么做的

str = "[curl] 6: blah blah 234433 blah blah";
mapObj = {'\\[curl] *': '', '\\d: *': ''};


function replaceAll (str, mapObj) {

    var arr = Object.keys(mapObj),
        re;

    $.each(arr, function (key, value) {
        re = new RegExp(value, "g");
        str = str.replace(re, function (matched) {
            return mapObj[value];
        });
    });

    return str;

}
replaceAll(str, mapObj)

返回"blah blah 234433 blah blah"

这样它将匹配mapObj中的键,而不是匹配的单词'


这招对我很管用:

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"

<!DOCTYPE html>
<html>
<body>



<p id="demo">Mr Blue 
has a           blue house and a blue car.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML;
    var res = str.replace(/\n| |car/gi, function myFunction(x){

if(x=='\n'){return x='<br>';}
if(x==' '){return x='&nbsp';}
if(x=='car'){return x='BMW'}
else{return x;}//must need



});

    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>

以防有人想知道为什么原来海报上的解决方案不管用:

var str = "I have a cat, a dog, and a goat.";

str = str.replace(/cat/gi, "dog");
// now str = "I have a dog, a dog, and a goat."

str = str.replace(/dog/gi, "goat");
// now str = "I have a goat, a goat, and a goat."

str = str.replace(/goat/gi, "cat");
// now str = "I have a cat, a cat, and a cat."

我写了这个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" 

使用正则函数定义要替换的模式,然后使用replace函数处理输入字符串,

var i = new RegExp('"{','g'),
    j = new RegExp('}"','g'),
    k = data.replace(i,'{').replace(j,'}');

用Jquery解决方案(首先包括这个文件):用多个其他字符串替换多个字符串:

var replacetext = {
    "abc": "123",
    "def": "456"
    "ghi": "789"
};

$.each(replacetext, function(txtorig, txtnew) {
    $(".eng-to-urd").each(function() {
        $(this).text($(this).text().replace(txtorig, txtnew));
    });
});

使用我的replace-once包,您可以执行以下操作:

const replaceOnce = require('replace-once')

var str = 'I have a cat, a dog, and a goat.'
var find = ['cat', 'dog', 'goat']
var replace = ['dog', 'goat', 'cat']
replaceOnce(str, find, replace, 'gi')
//=> 'I have a dog, a goat, and a cat.'

使用编号的物品,防止再次更换。 如

let str = "I have a %1, a %2, and a %3";
let pets = ["dog","cat", "goat"];

then

str.replace(/%(\d+)/g, (_, n) => pets[+n-1])

它的工作原理:- %\d+查找跟在%后面的数字。括号表示数字。

这个数字(作为字符串)是lambda函数的第二个参数n。

+n-1将字符串转换为数字,然后减去1以索引宠物数组。

然后将%数字替换为数组下标处的字符串。

/g导致lambda函数被重复调用,每个数字被替换为数组中的字符串。

在现代JavaScript中:-

replace_n=(str,...ns)=>str.replace(/%(\d+)/g,(_,n)=>ns[n-1])

    var str = "I have a cat, a dog, and a goat.";

    str = str.replace(/goat/i, "cat");
    // now str = "I have a cat, a dog, and a cat."

    str = str.replace(/dog/i, "goat");
    // now str = "I have a cat, a goat, and a cat."

    str = str.replace(/cat/i, "dog");
    // now str = "I have a dog, a goat, and a cat."

使用Array.prototype.reduce ():

更新(更好)答案(使用对象): 此函数将替换所有出现的情况,并且不区分大小写

/**
 * Replaces all occurrences of words in a sentence with new words.
 * @function
 * @param {string} sentence - The sentence to modify.
 * @param {Object} wordsToReplace - An object containing words to be replaced as the keys and their replacements as the values.
 * @returns {string} - The modified sentence.
 */
function replaceAll(sentence, wordsToReplace) {
  return Object.keys(wordsToReplace).reduce(
    (f, s, i) =>
      `${f}`.replace(new RegExp(s, 'ig'), wordsToReplace[s]),
      sentence
  )
}

const americanEnglish = 'I popped the trunk of the car in a hurry and in a hurry I popped the trunk of the car'
const wordsToReplace = {
  'popped': 'opened',
  'trunk': 'boot',
  'car': 'vehicle',
  'hurry': 'rush'
}

const britishEnglish = replaceAll(americanEnglish, wordsToReplace) 
console.log(britishEnglish)
// I opened the boot of the vehicle in a rush and in a rush I opened the boot of the vehicle

原始答案(使用对象数组):

    const arrayOfObjects = [
      { plants: 'men' },
      { smart:'dumb' },
      { peace: 'war' }
    ]
    const sentence = 'plants are smart'
    
    arrayOfObjects.reduce(
      (f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence
    )

    // as a reusable function
    const replaceManyStr = (obj, sentence) => obj.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence)

    const result = replaceManyStr(arrayOfObjects , sentence1)

Example // ///////////// 1. replacing using reduce and objects // arrayOfObjects.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence) // replaces the key in object with its value if found in the sentence // doesn't break if words aren't found // Example const arrayOfObjects = [ { plants: 'men' }, { smart:'dumb' }, { peace: 'war' } ] const sentence1 = 'plants are smart' const result1 = arrayOfObjects.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence1) console.log(result1) // result1: // men are dumb // Extra: string insertion python style with an array of words and indexes // usage // arrayOfWords.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence) // where arrayOfWords has words you want to insert in sentence // Example // replaces as many words in the sentence as are defined in the arrayOfWords // use python type {0}, {1} etc notation // five to replace const sentence2 = '{0} is {1} and {2} are {3} every {5}' // but four in array? doesn't break const words2 = ['man','dumb','plants','smart'] // what happens ? const result2 = words2.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence2) console.log(result2) // result2: // man is dumb and plants are smart every {5} // replaces as many words as are defined in the array // three to replace const sentence3 = '{0} is {1} and {2}' // but five in array const words3 = ['man','dumb','plant','smart'] // what happens ? doesn't break const result3 = words3.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence3) console.log(result3) // result3: // man is dumb and plants


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

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


为此,您可以使用https://www.npmjs.com/package/union-replacer。它基本上是一个字符串。Replace (regexp,…)对等体,它允许在一次传递中发生多次替换,同时保留string.replace(…)的全部功能。

披露:我是作者。开发这个库是为了支持更复杂的用户可配置替换,它解决了所有有问题的事情,比如捕获组、反向引用和回调函数替换。

上面的解决方案对于精确的字符串替换来说已经足够好了。


通过使用原型函数,我们可以通过传递对象的键和值以及可替换的文本轻松地进行替换

String.prototype.replaceAll =函数(obj keydata =“关键”){ const键= keydata.split(关键); 返回Object.entries (obj) .reduce((,(关键,val)) = > a.replace(“${键[0]}${关键}${键[1]}',val),) } Const data=' hidden dv SDC sd ${yathin} ${ok}' console.log (data.replaceAll ({yathin: 12,好的:“嗨”},“${关键}”))


所有的解决方案都很好,除了应用于闭包的编程语言(如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] ) );

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


我修改了本·麦考密克的答案以配合你的新测试用例。 我只是在正则表达式中添加了单词边界:

/\b(cathy|cat|catch)\b/gi

“运行代码片段”可以看到下面的结果:

var str = "我有一只猫,一个catch,和一个cathy."; var mapObj = { 凯茜:“猫”, 猫:“抓”, 抓住:“凯蒂” }; STR = STR .replace(/\b(cathy|cat|catch)\b/gi, function(matched){ 返回mapObj(匹配); }); console.log (str);


我们也可以使用split()和join()方法:

var str = "我有一只猫,一只狗,和一只山羊。"; str = str.split(“猫”)。映射(x =>{返回x.split("dog"))。地图(y = >{返回y.split(“山羊”). join(“猫”);}). join(“山羊”);}). join(“狗”); console.log (str);


作为对以下问题的回答:

寻找最新的答案

如果在当前示例中使用“words”,则可以使用非捕获组扩展Ben McCormick的答案,并在左侧和右侧添加单词边界\b以防止部分匹配。

\b(?:cathy|cat|catch)\b

防止部分匹配的单词边界 (?:非捕获组 Cathy |cat|catch匹配其中一个选项 )关闭非捕获组 防止部分匹配的单词边界

原问题的例子:

let str = "我有一只猫,一只狗和一只山羊。"; const mapObj = { 猫:“狗”, 狗:“山羊”, 山羊:“猫” }; str = str.replace(/\b(?:猫|狗|山羊)\b/gi, matched => mapObj[matched]); console.log (str);

评论中的例子似乎并没有很好地工作:

let str = "I have a cat, a catch and a cathy."; const mapObj = { 凯茜:“猫”, 猫:“抓”, 抓住:“凯蒂” }; str = str.replace(/\b(?:cathy|cat|catch)\b/gi, matched => mapObj[matched]); console.log (str);


这个解决方案可以只替换整个单词——例如,当搜索“猫”时,“catch”、“ducat”或“locator”将找不到。这可以通过对正则表达式中每个单词前后的单词字符使用负向后查找(?<!\w)和负向前查找(?!\w)来实现:

(?<!\w)(cathy|cat|ducat|locator|catch)(?!\w)

JSFiddle demo: http://jsfiddle.net/mfkv9r8g/1/


一种可能的解决方案是使用mapper表达式函数。

const regex = /(?:cat|dog|goat)/gmi;
const str = `I have a cat, a dog, and a goat.`;

let mapper = (key) => {
  switch (key) {
    case "cat":
      return "dog"
    case "dog":
      return "goat";
    case "goat":
      return "cat"
  }
}
let result = str.replace(regex, mapper);

console.log('Substitution result: ', result);
//Substitution result1:  I have a dog, a goat, and a cat.

你可以试试这个。买不聪明。

var str = "我有一只猫,一只狗,和一只山羊。"; console.log (str); str = str.replace(/cat/gi, "XXX"); console.log (str); STR = STR .replace(/goat/gi, "cat"); console.log (str); STR = STR .replace(/dog/gi, "goat"); console.log (str); str = str.replace(/XXX/gi, "dog"); console.log (str); 把: 我有一只狗,一只山羊和一只猫。


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

函数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 }