65.9K
CodeProject is changing. Read more.
Home

Trim, LTrim and RTrim Functions using Regular Expressions

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

Nov 8, 2010

CPOL
viewsIcon

26670

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()+"*");
Please do let me know, if you have any doubt. Please provide "Vote":thumbsup: Up if this would be helpful, and make "Accept Answer" if this would be correct answer.:rose: Thanks, Imdadhusen