How to distinguish jQuery selection strings from other strings

advertisements

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";
    }


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 );
    }