我正在嘗試用物件中的匹配項替換字串中的單詞。如果一個詞與物件的屬性匹配,它將被相關值替換。我的問題是在應該替換的單詞前后都有一個字符的情況,除非該字符是空格或連字符。
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 個屬性:值對,但并不總是匹配值
uj5u.com熱心網友回復:
您可以構建一個正則運算式來捕獲任何關鍵字,使用捕獲組來識別它是哪個關鍵字,并使用一個回呼函式來查找翻譯:
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));
可能需要將關鍵字從最長到最短排序,以便在較短的關鍵字也匹配時優先考慮較長的匹配項。
uj5u.com熱心網友回復:
我只想在這里使用一個交替。創建要查找的描述變體術語陣列,然后進行全域替換。
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/388751.html
標籤:javascript 正则表达式 细绳 目的 代替
上一篇:根據用戶輸入替換字串C
下一篇:c#中的字串處理?
