JQuery string contains check

2019-01-13 04:05发布

问题:

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?

回答1:

You can use javascript's indexOf function.

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



回答2:

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

sttr1.search(str2);

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



回答3:

Please try:

str1.contains(str2)


回答4:

Check out JavaScript's indexOf function. http://www.w3schools.com/jsref/jsref_IndexOf.asp



回答5:

I use,

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



回答6:

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

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

            alert("found");
        }


回答7:

simply on foreach loop with you can compare ,separated to strings

var commaseparateMainstring = 'shekar,jagadeesh,pavan,sai,suneel';
    var sustring = 'shekar,gopi,raju,suneel';
    //adding comma both sides of main string
    var main = ',' + commaseparateMainstring + ',';
    //substring change as array
    var substingArray = listToArray(sustring, ',');
    $.each(substingArray, function (index, value) {
        //calling is exist method here value means each value in substring
        var isexisted = isExist(main, value)
        if (isexisted) {
            //substring item existed
        }
        else {
        }
    });




//isExist method it checks substring exist in mainstring or not


function isExist(mainString, substring) {

if (mainString.indexOf(substring) != -1) {
    return true;
}
else {
    return false;
}
}


回答8:

This is working for me

if (~str.indexOf("Yes"))


回答9:

Below code you can check "hello" string is exit or not in given string.

if (our_string.indexOf('hello') > -1)
{
  alert("hello found inside our_string");
}

I hope this answer is useful for you.