标签云

微信群

扫码加入我们

WeChat QR Code

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.


Here a benchmark for the most common ways to check if a string is in a string: jsben.ch/#/o6KmH

2018年07月17日09分29秒

further to this answer, you could create function contains(haystack, needle) { return haystack.indexOf(needle) > -1; } Or even create one on the String prototype

2018年07月18日09分29秒

Jonathan I added a String.prototype function.

2018年07月17日09分29秒

thank you for the prototype function flexibility lesson!

2018年07月17日09分29秒

although this works, val > -1 is fewer operations

2018年07月17日09分29秒

zzzzBov, technically the !! Is unnecesary. So just the tilde would work.

2018年07月17日09分29秒

...depending on how strictly you need a boolean value. I agree, ~ will output the correct falsey state.

2018年07月17日09分29秒

I'm using JavaScript, but thanks :P

1970年01月01日00分03秒

Even better: var regex = /Hello, my name is jonh/; regex.test("Hello, my name is jonh LOL."); // true

2018年07月17日09分29秒