Click here to Skip to main content
Click here to Skip to main content

Trim, LTrim and RTrim Functions using Regular Expressions

, 9 Nov 2010
Rate this:
Please Sign up or sign in to vote.
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"Thumbs Up | :thumbsup: Up if this would be helpful, and make "Accept Answer" if this would be correct answer.Rose | [Rose]
 
Thanks,
Imdadhusen

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sunasara Imdadhusen
Software Developer (Senior) Infostretch Ahmedabad-Gujarat
India India
Aspiring for a challenging carrier wherein I can learn, grow, expand and share my existing knowledge in meaningful and coherent way.

sunaSaRa Imdadhusen
 
AWARDS:
  1. 1st Best Asp.Net article of SEP 2010
  2. 2nd Best Asp.Net article of MAY 2011
 
Read More Articles...
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
GeneralMy vote of 5 PinmemberSavalia Manoj M7-Nov-12 1:11 
GeneralRe: My vote of 5 PinpremiumSunasara Imdadhusen22-Apr-14 3:49 
GeneralEdit: Subject spelling, and other minor errors with spelling... PinmentorDaveAuld9-Nov-10 1:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 9 Nov 2010
Article Copyright 2010 by Sunasara Imdadhusen
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid