2

I'm trying to use the contains() function on my code and I need it to be case sensitive, which is supposed to be, but it's not. Whether I type

$("keyword:contains('{Keyword:')") 

or

$("keyword:contains('{KeyWord:')") 

It still works. What am I doing wrong? This is my JsFiddle : https://jsfiddle.net/xpvt214o/463834/

Thank you

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
Creek Barbara
  • 637
  • 1
  • 7
  • 29

2 Answers2

2

You need to check the $("keyword:contains('{Keyword:')").length rather than $("keyword:contains('{Keyword:')") in the if() condition

var keyword = '';
var elm = $("#message > p:contains('{Keyword:')");
if (elm.length) {
  keyword = elm.text().replace(/({Keyword:)/gi, "");
  keyword = keyword.replace(/}/gi, "");
  $("#message > p").text(keyword);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="message">
  <p>{Keyword:This is a headline}</p>
</div>
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
0

if ($("keyword:contains('{Keyword:')")){ ... } isn't matching against any conditional, and is simply returning a non-false value, so it triggers on everything (the var keyword = $("#message > p").text(); is targeting an arbitrary element.

The :contains selector should be used to target the specific element.

$("div.message > p:contains('{KeyWord:')").text(
  $("div.message > p:contains('{KeyWord:')").text().replace(/{keyword:/gi, "").replace(/}/gi, "")
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="message">
  <p>{KeyWord:This is a headline}</p>
</div>



<div class="message">
  <p>{Keyword:This is a headline}</p>
</div>
Matthew Moore
  • 866
  • 7
  • 10