Jquery selector contains equal sign

I am using jQuery selector to check characters in href:

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

This works fine until โ€œsomethingโ€ contains the โ€œ=โ€ sign. For instance:

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

then I do not get the result. Does anyone know a solution?

+6
source share
5 answers

You need to avoid the = character, since it has special meaning when used in jQuery selector . Here is a complete list of all characters that need to be escaped:

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

So you can use the following to exit param :

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

In the jQuery documentation:

If you want to use any of the metacharacters (for example ,! "# $% & '() * +,. / :; <=>? @ [] ^` {|} ~) As the literal part of the name, you should avoid the character with two backslashes: \.

Here is the demo .

+6
source

Enter parameter:

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

And if this is not enough ( param may contain apostrophes), then avoid them:

 $("a[href*='"+param.replace(/'/g,"\\'")+"']") 
+3
source

You need to avoid = with \\= .

 param = param.replace(/=/g, '\\\\='); 

But there are other special characters that you also need to hide in the jQuery selector.

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

You can also use the .filter method.

 $('a').filter(function() { return $(this).attr('href').indexOf(param) !== -1; }) 
+2
source

It behaves this way because in the end it translates into an ambiguous selector, i.e. $("a[href*=xkey=123]") , which is really invalid.

Exit the equal sign with \\ infront and wrap the quotation mark around part of the parameter

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

You can check it as follows:

Hope this matches the reason :)

foo is a string;

 if (! /^[a-zA-Z0-9]+$/.test(foo)) { // Validation failed } 

OR

Drop it like this check:

 if(your_string.indexOf('=') != -1){ alert("equal found."); } 

then replace = with \\=

0
source

Source: https://habr.com/ru/post/924234/


All Articles