1158

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.

3
  • 13
    Change your selector from $('select[id="Engraving"]') to $('#Engraving'). It will be faster. And inside the change handler, this refers to the #Engraving element, so you can do $(this).find('option:selected').
    – user113716
    Aug 13, 2010 at 21:33
  • How about :contains selector?
    – Oliver Ni
    Nov 28, 2013 at 21:02
  • 3
    What this has to do with jQuery? This is pure JavaScript question.
    – user182669
    Mar 1, 2014 at 7:28

12 Answers 12

2373

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
2
  • 35
    Can anyone explain the if (/yes/i.test(str))?
    – Drew S
    Feb 5, 2015 at 23:31
  • 56
    @DrewS: That's a regex literal.
    – SLaks
    Feb 5, 2015 at 23:45
137

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.

2
  • 27
    Good to know alternatives but using indexOf is faster. stackoverflow.com/questions/354110/…
    – Blowsie
    Feb 2, 2012 at 15:55
  • 3
    Be aware search uses regular expressions, so 'abc'.search('.') > -1 returns true even if there is no . character.
    – Oriol
    Apr 16, 2016 at 22:49
61

It's pretty late to write this answer, but I thought of including it anyhow. String.prototype now has a method includes which can check for substring. This method is case sensitive.

var str = 'It was a good date';
console.log(str.includes('good')); // shows true
console.log(str.includes('Good')); // shows false

To check for a substring, the following approach can be taken:

if (mainString.toLowerCase().includes(substringToCheck.toLowerCase())) {
    // mainString contains substringToCheck
}

Check out the documentation to know more.

1
  • how does this compare in performance? May 12, 2022 at 8:06
29

Another way:

var testStr = "This is a test";

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

** Tested on Firefox, Safari 6 and Chrome 36 **

1
  • getting error testStr.contains is not a function
    – adityaa72
    Dec 2, 2022 at 11:13
21

ECMAScript 6 introduces String.prototype.includes, previously named contains.

It can be used like this:

'foobar'.includes('foo'); // true
'foobar'.includes('baz'); // false

It also accepts an optional second argument which specifies the position at which to begin searching:

'foobar'.includes('foo', 1); // false
'foobar'.includes('bar', 1); // true

It can be polyfilled to make it work on old browsers.

0
13

The includes() method determines whether one string may be found within another string, returning true or false as appropriate.

Syntax :-string.includes(searchString[, position])

searchString:-A string to be searched for within this string.

position:-Optional. The position in this string at which to begin searching for searchString; defaults to 0.

string = 'LOL';
console.log(string.includes('lol')); // returns false 
console.log(string.includes('LOL')); // returns true 
0
10

You can use this Polyfill in ie and chrome

if (!('contains' in String.prototype)) {
    String.prototype.contains = function (str, startIndex) {
        "use strict";
        return -1 !== String.prototype.indexOf.call(this, str, startIndex);
    };
}
0
5

If you are capable of using libraries, you may find that Lo-Dash JS library is quite useful. In this case, go ahead and check _.contains() (replaced by _.includes() as of v4).

(Note Lo-Dash convention is naming the library object _. Don't forget to check installation in the same page to set it up for your project.)

_.contains("foo", "oo");     // → true
_.contains("foo", "bar");    // → false
// Equivalent with:
_("foo").contains("oo");     // → true
_("foo").contains("bar");    // → false

In your case, go ahead and use:

_.contains(str, "Yes");
// or:
_(str).contains("Yes");

..whichever one you like better.

0
4

I know that best way is str.indexOf(s) !== -1; http://hayageek.com/javascript-string-contains/

I suggest another way(str.replace(s1, "") !== str):

var str = "Hello World!", s1 = "ello", s2 = "elloo";
alert(str.replace(s1, "") !== str);
alert(str.replace(s2, "") !== str);

1

You can also check if the exact word is contained in a string. E.g.:

function containsWord(haystack, needle) {
    return (" " + haystack + " ").indexOf(" " + needle + " ") !== -1;
}

Usage:

containsWord("red green blue", "red"); // true
containsWord("red green blue", "green"); // true
containsWord("red green blue", "blue"); // true
containsWord("red green blue", "yellow"); // false

This is how jQuery does its hasClass method.

0

you can define an extension method and use it later.

String.prototype.contains = function(it) 
{ 
   return this.indexOf(it) != -1; 
};

so that you can use in your page anywhere like:

var str="hello how are you";
str.contains("are");

which returns true.

Refer below post for more extension helper methods. Javascript helper methods

0

None of the above worked for me as there were blank spaces but this is what I did

tr = table.getElementsByTagName("tr");

    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[0];
        bottab.style.display="none";
        bottab2.style.display="none";
        if (td) {
        var getvar=td.outerText.replace(/\s+/, "") ;

            if (getvar==filter){
                tr[i].style.display = "";
            }else{
                tr[i].style.display = "none";
            }

        }
    }

Not the answer you're looking for? Browse other questions tagged or ask your own question.