Tuesday, August 26, 2008

Adding contains(t) function to JavaScript String.prototype

The contains(t) function returns true if the string contains the value of the parameter "t" and false if it doesn’t. To extend the String.prototype with the contains(t) function I use this line of code:

String.prototype.contains = function(t) { return this.indexOf(t) >= 0 ? true : false }

This is sample code how to use the contains(t) function:

var sMyVar = new String (" testing text ");
alert(sMyVar.contains(’testing’));

//use it with the value of a text box
document.getElementById("txtMyTextBox").value.contains(’some text’);

No comments: