Extending JavaScript Strings with LINQ Style Contains Method

by Rick 24. August 2011 12:10

Similar to my previous post about extending JavaScrpt arrays to include a shuffle method... Any JavaScript object can be extended using the prototype object.  The following line of code deomonstrates how to extend JavaScript string objects to include a LINQ style contains method.  The function will return true if the string contains the input, or false, if it does not.

1
2
3
4
5
6
7
8
9
String.prototype.contains = function(input) {
     return ~this.indexOf(input)
}
 
var rickLeitch = "Rick Leitch";
 
if(rickLeitch.contains("ck Le")) {
     // Do Stuff
}

Currently rated 4.5 by 2 people

  • Currently 4.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , , ,

LINQ | JavaScript