我有字符串數組:如何查找缺少字母的匹配字符串?
var dict =["johndoe","johnrte","jahnaoi"];
我想打一個函數(正則表達式或其他),以檢查是否「STR」與缺失的字母適合的項目之一。缺少字母用「#」表示。 假設缺少字母的字符串是「j#hn#oe」。 我是以這種方式開始的,但我認爲我不會以正確的方式。
function Checkword(str) {
// Check were is the #
var indices = [0]
for (var i = 0; i < str.length; i++) {
if (str[i] === "#") indices.push(i);
}
var regexel = "/^";
for (var index = 0; index < indices.length; index++) {
regexel.concat(str.substring(indices[index - 1], indices[index]));
regexel.concat("[a-z]");
}
regexel.concat("$/");
var reg = new Regex(regexel);
for (r = 0; r < dict.length; i++) {
if (reg.test(dict[r]) {
console.log(dict[r]);
}
}
}
Checkword("j#hn#oe");
在這種情況下,它會返回第一個和最後一個項目。評論後
***編輯:
哪個字要經過我的測試:
If str is j#hndo#=> dict[0], dict[2].
If str is j####### => dict[0], dict[1], dict[2];
IF str is Jonh#oe=> dict[0]
if str is a#ze#ts=> nothing.
聽起來像一個面試問題 – Soren
你能澄清的問題是什麼? –
哪些字母在第一個和最後一個項目中缺失? '#' 沒有意義。 – sweaver2112