Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 369
The Mask Avatar asked Sep 01 '11 16:09

The Mask


People also ask

How do you check if a string exists in another string?

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.

How do you check if a string is in another string Python?

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!")

How do you check if a string exists in another string in JavaScript?

Definition and Usage. The includes() method returns true if a string contains a specified string. Otherwise it returns false .

How do I check if a string contains multiple substrings in Python?

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 .


2 Answers

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 
like image 57
Digital Plane Avatar answered Oct 15 '22 13:10

Digital Plane


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

like image 40
JaredPar Avatar answered Oct 15 '22 13:10

JaredPar