1147

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.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Jordan Garis
  • 11,489
  • 3
  • 16
  • 4
  • 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 '10 at 21:33
  • How about :contains selector? – Oliver Ni Nov 28 '13 at 21:02
  • 3
    What this has to do with jQuery? This is pure JavaScript question. –  Mar 01 '14 at 07:28

12 Answers12

2349

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
RedGuy11
  • 344
  • 6
  • 14
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
136

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.

hookedonwinter
  • 12,436
  • 19
  • 61
  • 74
  • 27
    Good to know alternatives but using indexOf is faster. http://stackoverflow.com/questions/354110/in-javascript-what-is-the-difference-between-indexof-and-search – Blowsie Feb 02 '12 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 '16 at 22:49
57

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.

Munim
  • 2,626
  • 1
  • 19
  • 28
29

Another way:

var testStr = "This is a test";

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

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

az7ar
  • 5,187
  • 2
  • 19
  • 23
Andy Braham
  • 9,594
  • 4
  • 48
  • 56
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.

Oriol
  • 274,082
  • 63
  • 437
  • 513
12

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 
Community
  • 1
  • 1
Parth Raval
  • 4,097
  • 3
  • 23
  • 36
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);
    };
}
robkorv
  • 549
  • 7
  • 5
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.

Selfish
  • 6,023
  • 4
  • 44
  • 63
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);
Sherali Turdiyev
  • 1,745
  • 16
  • 29
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.

bashaus
  • 1,614
  • 1
  • 17
  • 33
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

Vikas Kottari
  • 495
  • 2
  • 10
  • 24
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";
            }

        }
    }
Kingsley Mitchell
  • 2,412
  • 2
  • 18
  • 25