JQuery string contains check

2019-01-13 04:11发布

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?

9条回答
Explosion°爆炸
2楼-- · 2019-01-13 04:46
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楼-- · 2019-01-13 04:46

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;
}
}
查看更多
够拽才男人
4楼-- · 2019-01-13 04:47

You can use javascript's indexOf function.

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

查看更多
登录 后发表回答