Monday, 7 August 2017

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










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.


Answer



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

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...