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?
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.
Quote the parameter:
$("a[href*='"+param+"']")
And if that's not enough (param
may contain apostrophes) then escape them:
$("a[href*='"+param.replace(/'/g,"\\'")+"']")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With