Handling special characters in jQuery selectors

When we make dynamic id in Javascript sometimes it may happen that it can contain special characters like @/space/ something which might be difficult to access the element back using the jQuery selector.

So this article will help you manage such special characters so that the Javascript on that page does not break and throw any error for smooth accessing of the web page.

First create a function like below and place it in a common place where you will access it.

function escapeSelector( myid ) {
console.log(myid);
return myid.replace( /[:|.|[|]|,|=|@ ]/g, "\$&" );
}

Notice that the function accepts a parameter id which will escape the special characters using regex and then return it.

Now just call the above function whenver you are using jQuery selector to select that element.

For exmaple:

var element = $('tr[id^=' + escapeSelector(id) + ').attr("data-filename");

So the above line of code is selecting a particular td element with the id which is now being escaped to handle special characters.