在我的 React 程式中,假設我有以下字典/物件
const myDict = {
"a":"Value 1",
"b":"Value 2",
"hello":"Value 3",
"Bye":"Value 4"
}
(請注意,沒有任何鍵具有任何其他鍵中存在的值 - 例如,沒有鍵可以包含a字母,因為它是不同的鍵)
而且我將收到一個字串,該字串僅由該物件的鍵的排列組成,因此,例如,可能的字串條目將是:
- “阿布哈布”
- “阿巴拜耶你好”
- 《拜拜拜拜》
- 等等
我希望創建一個函式,該函式將根據myDict.
所以,例如,
"abhellob"會成為["a", "b", "hello", "b"]
我怎樣才能創建這樣的功能?我已經嘗試過,但是因為不得不處理不同長度的密鑰而迷失了方向myDict,我不知道該怎么做。
uj5u.com熱心網友回復:
在不同鍵之間交替的正則運算式可以解決問題。
const myDict = {
"a":"Value 1",
"b":"Value 2",
"hello":"Value 3",
"Bye":"Value 4"
}
const pattern = new RegExp(
Object.keys(myDict).join('|'),
'g'
);
console.log("abhellob".match(pattern));
console.log("ababByeahello".match(pattern));
console.log("ByehelloByeba".match(pattern));
(如果某些鍵可能有字符重疊,則首先對鍵進行排序,以便最長的鍵排在第一位。)
const myDict = {
"a":"Value 1",
"b":"Value 2",
"hello":"Value 3",
"Bye":"Value 4"
}
const pattern = new RegExp(
Object.keys(myDict)
.sort((a, b) => a.length - b.length)
.join('|'),
'g'
);
console.log("abhellob".match(pattern));
console.log("ababByeahello".match(pattern));
console.log("ByehelloByeba".match(pattern));
uj5u.com熱心網友回復:
您可以在沒有正則運算式的情況下執行此操作:
function getFragments(entryString){
const myDict = {
"a":"Value 1",
"b":"Value 2",
"hello":"Value 3",
"Bye":"Value 4"
}
const keys = Object.keys(myDict);
const result = [];
let remainingString = entryString;
while (remainingString) {
const nextWord = keys.find(key => remainingString.startsWith(key));
if (!nextWord) throw new Error("Couldn't match with word");
result.push(nextWord);
remainingString = remainingString.slice(nextWord.length);
}
return result;
}
console.log(getFragments("abhellob"));
console.log(getFragments("ababByeahello"));
console.log(getFragments("ByehelloByeba"));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/461352.html
標籤:javascript 细绳 功能 字典 解析
上一篇:轉換語法以進行預測分析
