what is the best way to check if a string exists in another?

Possible Duplicate:
JavaScript: string contains

I'm looking for an algorithm to check if a string exists in another.

For example:

'Hello, my name is jonh LOL.'.contains('Hello, my name is jonh'); //true
'LOL. Hello, my name is jonh'.contains('Hello, my name is jonh'); //true

Thanks in advance.


Use indexOf :

'Hello, my name is jonh LOL.'.indexOf('Hello, my name is jonh') > -1; //true
'LOL. Hello, my name is jonh'.indexOf('Hello, my name is jonh') > -1; //true

You can also extend String.prototype to have a contains function:

String.prototype.contains = function(substr) {
  return this.indexOf(substr) > -1;
}
'Hello, my name is jonh LOL.'.contains('Hello, my name is jonh'); //true
'LOL. Hello, my name is jonh'.contains('Hello, my name is jonh'); //true

As Digital pointed out the indexOf method is the way to check. If you want a more declarative name like contains then you can add it to the String prototype.

String.prototype.contains = function(toCheck) {
  return this.indexOf(toCheck) >= 0;
}

After that your original code sample will work as written


How about going to obscurity:

!!~'Hello, my name is jonh LOL.'.indexOf('Hello, my name is jonh'); //true
if(~'LOL. Hello, my name is jonh'.indexOf('Hello, my name is jonh'))
    alert(true);

Using Bitwise NOT and to boolean NOTs to convert it to a boolean than convert it back.

链接地址: http://www.djcxy.com/p/2048.html

上一篇: 如果句子包含字符串

下一篇: 检查另一个字符串是否存在的最佳方法是什么?