Search code examples
jqueryjquery-selectorsanythingslider

How to test if selector is valid in jQuery


I am using AnythingSlider jQuery plugin which dynamically reads the hash in the URL and selects an item on a page via jQuery. The problem is the end user can break the plugin if they get to http://mydomain.com/#!demos/slider.

Is there a way to test if a selector is valid instead of letting jQuery crashing (built in function or regex)? See this jsFiddle example that tries to do $('#!demos/slider') and it crashes: http://jsfiddle.net/PvY2b/

$('#!demos/slider') <= Uncaught Error: Syntax error, unrecognized expression: #!demo/slider

Solution

  • ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

    From: Basic HTML data types

    Therefore something like this might work:

    if (/^[A-Za-z][A-Za-z0-9\-_:\.]*$/.test(selector)) {
        // $('#' + selector)...
    }
    

    Or simply escape it:

    selector = selector.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');