Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if string contains substring? [duplicate]

I have a shopping cart that displays product options in a dropdown menu and if they select "yes", I want to make some other fields on the page visible.

The problem is that the shopping cart also includes the price modifier in the text, which can be different for each product. The following code works:

$(document).ready(function() {     $('select[id="Engraving"]').change(function() {         var str = $('select[id="Engraving"] option:selected').text();         if (str == "Yes (+ $6.95)") {             $('.engraving').show();         } else {             $('.engraving').hide();         }     }); }); 

However I would rather use something like this, which doesn't work:

$(document).ready(function() {     $('select[id="Engraving"]').change(function() {         var str = $('select[id="Engraving"] option:selected').text();         if (str *= "Yes") {             $('.engraving').show();         } else {             $('.engraving').hide();         }     }); }); 

I only want to perform the action if the selected option contains the word "Yes", and would ignore the price modifier.

like image 406
Jordan Garis Avatar asked Aug 13 '10 21:08

Jordan Garis


People also ask

How do you check if a string contains a specific substring?

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.


1 Answers

Like this:

if (str.indexOf("Yes") >= 0) 

...or you can use the tilde operator:

if (~str.indexOf("Yes")) 

This works because indexOf() returns -1 if the string wasn't found at all.

Note that this is case-sensitive.
If you want a case-insensitive search, you can write

if (str.toLowerCase().indexOf("yes") >= 0) 

Or:

if (/yes/i.test(str)) 

The latter is a regular expression or regex.

Regex breakdown:

  • / indicates this is a regex
  • yes means that the regex will find those exact characters in that exact order
  • / ends the regex
  • i sets the regex as case-insensitive
  • .test(str) determines if the regular expression matches str To sum it up, it means it will see if it can find the letters y, e, and s in that exact order, case-insensitively, in the variable str
like image 115
SLaks Avatar answered Sep 21 '22 14:09

SLaks