Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery selector contains equals sign

I am using a jQuery selector to check for characters in href:

var param = "something";
$("a[href*="+param+"]").css("color", "red");

This works fine until "something" contains an = sign. Eg:

var param = "xkey=123";
$("a[href*="+param+"]").css("color", "red");

then I get no result. Anyone know a solution?

like image 329
John Buckwell Avatar asked Aug 31 '12 03:08

John Buckwell


2 Answers

You need to escape the = character since it has a special meaning when used in a jQuery selector. Here's the full list of all characters that need to be escaped:

#;&,.+*~':"!^$[]()=>|/

Thus, you can use the following to escape the param:

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

From the jQuery documentation:

If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \.

Here's a DEMO.

like image 180
João Silva Avatar answered Sep 17 '22 23:09

João Silva


Quote the parameter:

$("a[href*='"+param+"']")

And if that's not enough (param may contain apostrophes) then escape them:

$("a[href*='"+param.replace(/'/g,"\\'")+"']")
like image 44
Niet the Dark Absol Avatar answered Sep 17 '22 23:09

Niet the Dark Absol