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

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

当前回答

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

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

其他回答

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

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中的键,而不是匹配的单词'

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

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

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

作为对以下问题的回答:

寻找最新的答案

如果在当前示例中使用“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);

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

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

使用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