开发者

jquery check is string is inside a string

I got 2 variables;

value = 'com'; longString= "com-233-123-232-123";

I'd like to check if "value" is inside "longString". I tried using regex with test() but I开发者_StackOverflow中文版 fail, maybe you know better.


I think the indexOf(substr, [start]) is enough no need to regex.

indexOf(substr, [start]) 

Searches and (if found) returns the index number of the searched character or substring within the string. If not found, -1 is returned. "Start" is an optional argument specifying the position within string to begin the search. Default is 0.

http://www.javascriptkit.com/javatutors/string4.shtml


Two ways

1st indexOf

if (longString.indexOf(value) != -1)
   // found
else
   // not found

2nd split

var value = 'com'; var longString= "com-233-123-232-123";
var split1=longString.split("-");
var i=0;
var found=0;
while (i<split1.length)
{
    if(split1[i]==value)
    {
        found=1;
        break;
    }
    i++;
}
if(found==1)
    //found
else
    //not found


Don't use regular expressions for this - if the value you're looking for can be interpreted as a regular expression itself then you'll have trouble. Just check for longString.indexOf(value) != -1.


What does jQuery has to do with this? This is a simple Javascript problem

if (longString.indexOf(value) != -1)
    // We found it
else
   // We didn't find it
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜