133

I need to check whether a string contains another string or not?

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";

Which function do I use to find out if str1 contains str2?

2
  • a benchmark of different solutions can be found here: jsben.ch/#/RVYk7 Commented Nov 11, 2016 at 10:24
  • @EscapeNetscape: Nice to see a benchmark link. If I change the observation string to a very long UTF-8 multibyte text, the results change drastically? Also, the results changed with change in position of substring in the observation string. BTW, which one were you suggesting. Commented Feb 21, 2019 at 12:27

5 Answers 5

298

You can use javascript's indexOf function.

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
    console.log(str2 + " found");
}

Sign up to request clarification or add additional context in comments.

8 Comments

this would works only when substring has exact match, will not work around "DEfG" as f is small case.
@RedSwan: you could convert the string to uppercase or lowercase and then do the comparison, problem solved.
@mulllhausen: It's 2016, this answer is 6 years old, and most sites have stopped supporting IE < 9.
@RocketHazmat: fair enough. I just commented because it wasn't mentioned in any of the answers on this page and people may be interested to know.
|
18
var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";

sttr1.search(str2);

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

2 Comments

It would be nice to note that Array.prototype.search implicitly converts the string to a regular expression which may not give the desired result.
Last row should be: str1.search(str2); not sttr1, IMHO
11

I use,

var text = "some/String"; text.includes("/") <-- returns bool; true if "/" exists in string, false otherwise.

1 Comment

Nice, simple and straight to the point!
9

Please try:

str1.contains(str2)

4 Comments

CurrentPage.contains is not a function
It's because .contains() is a jQuery method.
I get contains is not a function
That's how it's done $(":contains('Hello')")
5

If you are worrying about Case sensitive change the case and compare the string.

 if (stringvalue.toLocaleLowerCase().indexOf("mytexttocompare")!=-1)
        {

            alert("found");
        }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.