How do I check if string contains substring?

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.

Text Copied From stackoverflow.com
on : Fri, Aug 13, 2010 Views : 1321170

Accepted Answer

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)) 
Text Copied From stackoverflow.com
on : Fri, Aug 13, 2010

Ask Question

If you want to ask question you must LogIn or SignUp
Login SignUp

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp