字符串是HTML还是Selector?JavaScript



我从这里拿了一些代码: - 如何将jQuery选择器字符串与其他字符串区分开 - 并对其进行了一些修改。但是,我无法让比赛正常工作。我尝试了.test.exec

var htmlExpr = /^(?:[^<]*(<[wW]+>)[^>]*$|#([w-]+)$)/;
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 || htmlExpr.test( selector )) {
    return true;
} else {
    return false;
}

我正在使用#mydiv<div class='gallery'>gallery</div>blah作为selector

都返回true。

我想念的是什么?

#mydiv在此部分|#([w-]+)$中的正则返回时,返回了True,您应该消除该部分,因此#mydiv不匹配,例如:

function isHtml(selector) {
    var htmlExpr = /^[^<]*(<[wW]+>)[^>]*$/;
    if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 || htmlExpr.test( selector )) {
        return true;
    } else {
        return false;
    }
} 
// Demo
console.log(isHtml("#mydiv")); // false
console.log(isHtml("<div class='gallery'>gallery</div>blah")); // true

最新更新