gpt4 book ai didi

javascript - 用JS中对象的匹配项替换单词

转载 作者:行者123 更新时间:2023-12-05 03:32:41 25 4
gpt4 key购买 nike

我正在尝试用对象中的匹配项替换字符串中的单词。如果一个词与对象的属性相匹配,它将被相关值替换。我的问题是在应该替换的单词前后有一个字符的情况,除非该字符是空格或连字符。

function fixTypos(str) {
var typoObject = {
descriptiogn:'description',
decscription:'description',
vdescription:'description',
wdescription:'description',
descriptiog:'description',
statucs:'status',
statuqs:'status',
cstatus:'status',

for (var key in typoObject) {
str = str.replace(new RegExp(`\\b${key}\\b`, "gi"), typoObject[key]);
}
return str;
}

teststring: 'word -decscription word2 adescriptiogn word3 -astatucs'

当前输出:'word -description word2 adescriptiogn word3 -astatucs'

期望的输出:'word -description word2 description word3 -status'

我的方法可能是错误的,因为我开始怀疑它是否可以通过正则表达式完成,但也许这里有人对我有想法?

编辑:在对象中添加了更多种类。该对象是一个示例,但我在我的项目中使用的对象包含超过 2k 个属性:值对,但值并不总是匹配

最佳答案

您可以构建一个正则表达式来捕获任何关键字,使用捕获组来识别它是什么,并使用回调函数来查找翻译:

const translation = {
descriptiogn:'description',
decscription:'description',
vdescription:'description',
wdescription:'description',
descriptiog:'description',
statucs:'status',
statuqs:'status',
cstatus:'status',
};
const regex = new RegExp("\\b\\w*("
+ Object.keys(translation)
.sort((a, b) => b.length - a.length)
.join("|")
+ ")\\w*\\b", "g");

const fixTypos = str => str.replace(regex, (_, match) => translation[match]);

const teststring= 'word -decscription word2 adescriptiogn word3 -astatucs'

console.log(fixTypos(teststring));

可能需要将关键字从最长到最短排序,以便在较短的关键字也匹配时优先考虑较长的匹配项。

关于javascript - 用JS中对象的匹配项替换单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70418053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com