what is the best way to check if a string exists in another? [duplicate]
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.
another option could be to match a regular expression by using match(): http://www.w3schools.com/jsref/jsref_match.asp.
> var foo = "foo";
> console.log(foo.match(/bar/));
null
> console.log(foo.match(/foo/));
[ 'foo', index: 0, input: 'foo' ]
I would suppose that using pre-compiled Perl-based regular expression would be pretty efficient.
RegEx rx = new Regex('Hello, my name is jonh', RegexOptions.Compiled);
rx.IsMatch('Hello, my name is jonh LOL.'); // true
精彩评论