JQuery string contains check [duplicate]
Asked Answered
T

5

131

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?

Talus answered 16/9, 2010 at 15:9 Comment(2)
a benchmark of different solutions can be found here: jsben.ch/#/RVYk7Shanley
@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.Devondevona
E
295

You can use javascript's indexOf function.

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
    console.log(str2 + " found");
}
Eavesdrop answered 16/9, 2010 at 15:11 Comment(8)
this would works only when substring has exact match, will not work around "DEfG" as f is small case.Panthea
@RedSwan: you could convert the string to uppercase or lowercase and then do the comparison, problem solved.Talus
indexOf() is not supported in IE < 9Fellner
@mulllhausen: It's 2016, this answer is 6 years old, and most sites have stopped supporting IE < 9.Eavesdrop
@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.Fellner
For clarity, you should use === instead of ==Metallography
@DeepSojitra jQuery is not a language. It's a JavaScript library. The jQuery library does not contain this function, it's part of the JavaScript language. Also this question is 11 years old and this answer was accepted.Eavesdrop
@RedSwan or you could also use indexOf("DEfG", StringComparison.OrdinalIgnoreCase);Depose
S
17
var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";

sttr1.search(str2);

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

Sorrento answered 28/2, 2014 at 2:29 Comment(2)
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.Foley
Last row should be: str1.search(str2); not sttr1, IMHOBrother
I
10

Please try:

str1.contains(str2)
Incense answered 2/7, 2014 at 2:35 Comment(4)
CurrentPage.contains is not a functionHluchy
It's because .contains() is a jQuery method.Glaydsglaze
I get contains is not a functionAmylose
That's how it's done $(":contains('Hello')")Dilemma
B
9

I use,

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

Batruk answered 14/2, 2017 at 23:3 Comment(0)
H
5

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

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

            alert("found");
        }
Hluchy answered 19/7, 2016 at 10:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.