如何在JavaScript中一次替换多个单词

epggiuax  于 2023-10-14  发布在  Java
关注(0)|答案(3)|浏览(87)

.replace(/\w+/g), function)在替换standardizeMap中的一个单词时工作良好,但是,当涉及到多个单词时,它会失败。
示例输入(情况1):

const standardizeMap = new Map([
    ["Hello world", "How are you"],
    ["apple pen", "appleP"],
    ["Swaziland", "Eswatini"])
"Hello world I have an apple pen in Swaziland".replace(/\w+/g, (word) =>
        standardizeMap.get(word) ? standardizeMap.get(word) : word
      )

输出量:

Hello world I have an apple pen in Eswatini

预期输出:

How are you I have an appleP in Eswatini

示例输入(情况2):

"Hello world I have an apple penin Swaziland".replace(/\w+/g, (word) =>
        standardizeMap.get(word) ? standardizeMap.get(word) : word
      )

预期输出:

How are you I have an apple penin Eswatini

我怎么才能做到呢?

rkttyhzu

rkttyhzu1#

如果你换个方式工作可能会更好。循环遍历Map,并替换在Map中与项目匹配的文本中找到的整个单词:

const standardizeMap = new Map([
  ['Hello world', 'How are you'],
  ['apple pen', 'appleP'],
  ['Swaziland', 'Eswatini'],
])

let text1 = 'Hello world I have an apple pen in Swaziland'
let text2 = 'Hello world I have an apple penin Swaziland'

function replaceText(text, map) {
  for (let [key, value] of map) {
    let re = new RegExp(`\\b${key}\\b`, 'g')
    text = text.replace(re, value)
  }

  return text
}

console.log(replaceText(text1, standardizeMap))
console.log(replaceText(text2, standardizeMap))
ckx4rj1h

ckx4rj1h2#

调用String.replace(/\w+/g, (word) => doStuff())(或replaceAll,same thing except that replaceAll requires the 'g' flag)将让该方法对\w+的每个匹配序列执行替换。您可以使用控制台日志记录来查看它们:

>> let text = "Hello world I have an apple pen in Swaziland";
>> text.replace(/\w+/g, function(word) {console.log(word);return word});
Hello
world
I
have
an
apple
pen
in
Swaziland

所以,你应该遍历你的map,对于每个条目,在文本中将所有出现的键替换为它的值。
相反,您应该循环遍历您的map,并且对于每个条目,在文本中将条目的键的所有出现替换为它的值,例如如下所示。

let text = "Hello world I have an apple pen in Swaziland" ;
for (const [key, value] of standardizeMap) {
    text = text.replaceAll(key, value);
}
bjp0bcyl

bjp0bcyl3#

您需要替换standardizeMap中的每个键值,并替换所有出现的键。

const standardizeMap = new Map([
  ["Hello world", "How are you"],
  ["apple pen", "appleP"],
  ["Swaziland", "Eswatini"],
]);

const input = "Hello world I have an apple pen in Swaziland";

function replaceString(map, input) {
  let output = input;
  for (const [key, value] of map) {
    output = output.replace(key, value);
  }
  return output;
}

console.log(replaceString(standardizeMap, input));

相关问题