我有字符串数组:如何查找缺少字母的匹配字符串?
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