我想通過字符的位置找到一個單詞:
const wordlist = ['xenon', 'rewax', 'roger', 'bob', 'xylophone']
而且,要找到木琴,我將擁有:
const charSlotPairs = [{char: "x", slot: 0}, {char: "y", slot: 1}];
所以我正在動態構建正則運算式(^.{0}[x])(^.{1}[y])
,但我認為這個正則運算式是錯誤的......如何根據字串中字符的位置找到匹配項?
function (charSlotPairs){
let regexStr = ""
charSlotPairs.forEach( pair => {
regexStr = `(^.{${pair.slot}}[${pair.char}])`
})
const regex = new RegExp(`${regexStr}\\w`, 'g')
return this.filter( word => !word.match(regex) )
}
uj5u.com熱心網友回復:
這是我解決它而不是使用正則運算式的方法:
function (charSlotPairs){
return !!charSlotPairs.find(pair =>
a.find( word =>
word.charAt(pair.slot) == pair.char)
)
}
uj5u.com熱心網友回復:
您的查詢只能使用回圈來解決。
const wordlist = ['xenon', 'rewax', 'roger', 'bob', 'xylophone'];
const charSlotPairs = [{char: "x", slot: 0}, {char: "y", slot: 1}];
let stringFinder = (StrArr, KeyArr) =>
{
var match = false; // Indicator Variable
// For Iterating a String Array
for (var i of StrArr)
{
// For Iterating the Object Array for each Key
for (var x of KeyArr)
{
/*
|If Conditon fails, match will set to false and Loop will Break
|Otherwise Loop will continue
*/
if (i.charAt(x.slot) != x.char)
{
match = false;
break;
}
else
{
match = true;
}
}
/*
|If the Inner Loop is completed and match is true => Success
|If the Inner Loop is completed and match is false => Failed
*/
if (match)
{
return i;
}
}
return false;
}
console.log(stringFinder(wordlist, charSlotPairs));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/418897.html
標籤:
