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

replace word with match from object in JS

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

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

测试字符串:'word -decscription word2 adescriptiogn word3 -astatucs'

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

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

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

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

我只是在这里使用交替。创建一个描述变体术语的数组来查找,然后进行全局替换。

var input = 'word -decscription word2 adescriptiogn word3 -adescriptiogn';
var terms = ['descriptiogn', 'decscription', 'vdescription', 'wdescription', 'descriptiog'];
var regex = new RegExp("\b\w*(?:" + terms.join("|") + ")\w*\b", "g");
var output = input.replace(regex, "description");
console.log(input);
console.log(output);

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

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

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