Trim function in javascript using prototype

by rajesh 2007-11-29 15:21:15

This is a function that can be used to do trim operation on any javascript string variable.

String.prototype.trim = function() {
return this.replace(/^s+|s+$/g,"");
}


We have added add a new function to the String Object itself. So it can be used as any other string functions like indexOf() or split() or charAt()....

Usage:

String.prototype.trim = function() {
return this.replace(/^s+|s+$/g,"");
}

var str = "sdfsdf ";
var result = str.trim();
alert(result);


The result will not have the space in the end.

We can add functions to any javascript objects like String, Array etc using the prototype call. May be I or some one will write later on prototypes in javascript....

Tagged in:

1374
like
0
dislike
0
mail
flag

You must LOGIN to add comments