Search code examples
javascripthtmlregexstringselector

String is html or selector? javascript


I took some code from here: - How do I distinguish jQuery selector strings from other strings - and modified it a bit. However, I CANNOT get the match to work correctly. I've tried both .test and .exec.

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

I'm using #mydiv and <div class='gallery'>gallery</div>blah as selector

Both return true.

What's going on here that I'm missing?


Solution

  • #mydiv is returning true as you've specifically check for it in the regex in this part |#([\w\-]+)$ , you should eliminate that part so #mydiv doesn't match, like this:

    function isHtml(selector) {
        var htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$/;
        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