Friday, November 03, 2006

Trim, ltrim, rtrim / strip, lstrip, rstrip fucntions for javascript

In programming, trim or strip is a string manipulation function or algorithm which removes leading and trailing whitespace from a string. ltrim removes only leading trailing whitespaces and rtrim removes only trailing whitespaces and trim removes both leading and trailing whitespaces.
Trim, ltrim and rtrim are also known as strip, lstrip and rstrip, respectively.

Javascript does not have its own trim or strip function. But you can define your own. Write the codes given below in your source code and you can use them as you do in other languages. Take care, that these codes should be written in your code before they are called.

trim:

String.prototype.trim = function() {
return this.replace(/^\s*|\s*$/g, "")
}
ltrim:
String.prototype.trim = function() {
return this.replace(/^\s*/g, "")
}
rtrim:
String.prototype.trim = function() {
return this.replace(/\s*$/g, "")
}
After writing the above codes you can use the functions normally. A few examples are:-
trimmed_str=str.trim();
trimmed_str=' someString '.trim();
str=str.ltrim();
str=str1.rtrim() + str2.rtrim();

TechnoratiTechnorati: , ,

No comments: