DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Remove Space Using Trim, LTrim And RTrim Using Regular Expressions

12.19.2011
| 4761 views |
  • submit to reddit
        Trim: remove whitespace from the start and end(both sides) of the string.
LTrim: remove start whitespace of the string.
RTrim: remove end whitespace of the string.
Rather than using a clumsy loop, use a simple, elegant regular expression.

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}
 
Example:-
// example of using trim, ltrim, and rtrim
var myString = " hello my name is imdadhusen  ";
alert("*"+myString.trim()+"*");
alert("*"+myString.ltrim()+"*");
alert("*"+myString.rtrim()+"*");

<a href="http://www.java-forums.org/java-software/"><strong>Java Software</strong></a>