实现一个函数,如果给定的字符串与给定的通配符模式匹配,则返回True,否则为

时间:2017-03-05 19:42:38

标签: javascript wildcard contains

实现一个函数,如果给定的字符串与给定的通配符模式匹配,则返回True,否则返回False。

允许使用内置的split()indexOf()startsWith()endsWith()

这与我做的最后一次非常相似,但我似乎仍然无法掌握它。这是我到目前为止所拥有的



function matches(text, pattern) {
    var x = pattern.split("*");
    var y = (text.indexOf(x[0]) !== -1);
    for (i = 0; i< x.length; i++){
        if (y) {
            y = (text.indexOf(x[i]) !== -1);
        }
    }
    return y;
}

console.log(matches("lord of the rings", "lord*rings")); // Expected: True
console.log(matches("lord of the rings", "Lord*rings")); // Expected: False
console.log(matches("lord of the rings", "l*o*t*r")); // Expected: False
console.log(matches("lord of the rings", "l*o*t*r*s")); // Expected: True
console.log(matches("lord of the rings", "lord*")); // Expected: True
console.log(matches("lord of the rings", "*rings")); // Expected: True
console.log(matches("lord of the rings", "*the*")); // Expected: True
console.log(matches("lord of the rings", "*")); // Expected: True
console.log(matches("lord of the rings", "*z*")); // Expected: False
&#13;
&#13;
&#13;

我想要做的是隔离单词,然后检查每一个单词,如果所有单词都存在,那么我返回true或者如果其中至少有一个不返回false ### Message 'msg.test.validation' not found ### 。但出了点问题,我不太明白是什么。

非常感谢解决方案或对我的代码的反馈,请保持相当简单。 谢谢!

1 个答案:

答案 0 :(得分:0)

function matches(text, pattern) {
    while (text.length) {
        if (text[0] !== pattern[0] && pattern[0] !== '*')
            return false;

        text = text.slice(1);

        var wordAfterWildcard = pattern.split('*')[1];

        if (pattern[0] !== '*' || wordAfterWildcard && text.startsWith(wordAfterWildcard))
            pattern = pattern.slice(1);
    }
    return !(pattern && pattern.replace('*', ''));
}

//我做了功课,因为我是个疯子。不是因为你。 //享受......