JQuery string contains check

JavascriptJqueryStringComparisonContains

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

You can use javascript's indexOf function.

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

Solution 2 - Javascript

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

sttr1.search(str2);

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

Solution 3 - Javascript

Please try:

str1.contains(str2)

Solution 4 - Javascript

I use,

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

Solution 5 - Javascript

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

 if (stringvalue.toLocaleLowerCase().indexOf("mytexttocompare")!=-1)
        {
            
            alert("found");
        }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondiggersworldView Question on Stackoverflow
Solution 1 - JavascriptRocket HazmatView Answer on Stackoverflow
Solution 2 - JavascriptKhaihkdView Answer on Stackoverflow
Solution 3 - JavascriptscottView Answer on Stackoverflow
Solution 4 - Javascripteaglei22View Answer on Stackoverflow
Solution 5 - JavascriptmzonerzView Answer on Stackoverflow