How do I distinguish jQuery selector strings from

2019-07-18 12:20发布

问题:

I want to check the 'type' of a string. Particularly, how do I distinguish jQuery selector strings from other strings? In other words, how should selectorTest be implemented in the following code?

    var stringType = function( value ) {   
        var htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$/;

        if ( htmlExpr.test(value) ) {
            return "htmlstring";
        }
        if ( selectorTest ) {
            return "selectorstring";  
        }
        return "string";
    }

回答1:

You can do what jQuery does internally and check if it's HTML or not with the following regex:

/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/

e.g.:

var stringType = function( value ) {   
    var htmlExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/;

    if ( htmlExpr.test(value) ) {
        return "htmlstring";
    }
    if ( selectorTest ) {
        return "selectorstring";  
    }
    return "string";
}

Note that in more recent versions of jQuery, there's another check explicitly for "starting with <" and "ending with >" to skip the regex (purely for speed). The check looks like this in core (as of jQuery 1.6.1):

if ( typeof selector === "string" ) {
    // Are we dealing with HTML string or an ID?
    if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
        // Assume that strings that start and end with <> are HTML and skip the regex check
        match = [ null, selector, null ];
    } else {
        match = quickExpr.exec( selector );
    }


回答2:

maybe ($(value).size()>0) ?

It will test if the selector is recognized.

But in my opinion, it is a bit strange way to do...