Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How do I check if string contains substring?

I have a shopping cart that presents item alternatives in a dropdown menu and in the menu that they select "yes", I need to make some different fields on the page apparent.

The issue is that the shopping cart additionally remembers the value modifier for the content, which can be diverse for every item. The accompanying 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.
by

2 Answers

aashaykumar
You could use search or match for this.

str.search( 'Yes' )


will return the position of the match, or -1 if it isn't found.
RoliMishra
Another way:

var testStr = "This is a test";

if(testStr.contains("test")){
alert("String Found");
}

Login / Signup to Answer the Question.