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

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

当前回答

使用我的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])

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

使用我的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.'

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

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

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

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."