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

12

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.

Elwira answered 13/8, 2010 at 21:25 Comment(3)
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').Gianna
How about :contains selector?Erratic
What this has to do with jQuery? This is pure JavaScript question.Wittenburg
S
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
Sesquioxide answered 13/8, 2010 at 21:28 Comment(2)
Can anyone explain the if (/yes/i.test(str))?Dekaliter
@DrewS: That's a regex literal.Sesquioxide
G
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.

Gondola answered 13/8, 2010 at 21:29 Comment(2)
Good to know alternatives but using indexOf is faster. #354610Buckeye
Be aware search uses regular expressions, so 'abc'.search('.') > -1 returns true even if there is no . character.Clothier
D
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.

Danforth answered 7/5, 2016 at 13:38 Comment(1)
how does this compare in performance?Minyan
D
29

Another way:

var testStr = "This is a test";

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

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

Delores answered 20/2, 2013 at 19:44 Comment(1)
getting error testStr.contains is not a functionCounty
C
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.

Clothier answered 16/4, 2016 at 23:0 Comment(0)
C
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 
Cedric answered 18/11, 2016 at 17:45 Comment(0)
L
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);
    };
}
Ligniform answered 3/7, 2013 at 14:9 Comment(0)
M
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.

Modestamodeste answered 1/10, 2015 at 6:18 Comment(0)
D
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);
Displant answered 1/10, 2015 at 6:5 Comment(0)
C
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.

Cha answered 26/3, 2015 at 15:43 Comment(0)
S
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

Slabber answered 3/3, 2015 at 13:8 Comment(0)
L
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";
            }

        }
    }
Limacine answered 17/7, 2017 at 0:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.