jquery contains selector not working for \ (Back Slash)

Viewed 259

jquery contains selector not working for \ (back slash). Please find the code below

Java Script:

$(document).ready(function(){
  $("p:contains(Example:\\servername)").css("background-color", "yellow");
   
});

HTML

<p>Example:\\servername</p>
2 Answers

$(document).ready(function() {
  $("p:contains('Example:\\\\\\\\\\servername')").css("background-color", "yellow");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Example:\\servername</p>
8 and 10 backslashes work properly but when its 2 only one will escape other and it doesn't make sense when there are four also you get no result but 8 and 10 works and its not good idea to write all of those back slashes what you to do is to write one only followed by none character this doesn't cause any error

$(document).ready(function() {
  $("p:contains('Example:\')").css("background-color", "yellow");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Example:\\servername</p>

Unfortunately the \ need escaping with another \ and I don't think you can do it with :contains selector.

You can do it using filter()

let p=$("p").filter(function(){    
   return $(this).text().includes('Example:\\\\servername')
}).css("background-color", "yellow");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Example:\\servername</p>

Related