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.
You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.
The in Operator It returns a Boolean (either True or False ). To check if a string contains a substring in Python using the in operator, we simply invoke it on the superstring: fullstring = "StackAbuse" substring = "tack" if substring in fullstring: print("Found!") else: print("Not found!")
Definition and Usage. The includes() method returns true if a string contains a specified string. Otherwise it returns false .
You can use any : a_string = "A string is more than its parts!" matches = ["more", "wholesome", "milk"] if any(x in a_string for x in matches): Similarly to check if all the strings from the list are found, use all instead of any .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With