FAQ Topic - How do I trim whitespace - LTRIM/RTRIM/TRIM?

Discussion in 'Javascript' started by FAQ server, Oct 26, 2006.

  1. FAQ server

    FAQ server Guest

    -----------------------------------------------------------------------
    FAQ Topic - How do I trim whitespace - LTRIM/RTRIM/TRIM?
    -----------------------------------------------------------------------

    Using Regular Expressions (JavaScript 1.2/JScript 4+) :

    String.prototype.LTrim=new Function("return this.replace(/^\\s+/,'')")
    String.prototype.RTrim=new Function("return this.replace(/\\s+$/,'')")
    String.prototype.Trim=
    new Function("return this.replace(/^\\s+|\\s+$/g,'')")

    or for all versions (trims characters ASCII<32 not true
    "whitespace"):

    function LTrim(str) {
    for (var k=0; k<str.length && str.charAt(k)<=" " ; k++) ;
    return str.substring(k,str.length);
    }
    function RTrim(str) {
    for (var j=str.length-1; j>=0 && str.charAt(j)<=" " ; j--) ;
    return str.substring(0,j+1);
    }
    function Trim(str) {
    return LTrim(RTrim(str));
    }

    http://msdn.microsoft.com/library/en-us/script56/html/js56reconIntroductionToRegularExpressions.asp

    http://docs.sun.com/source/816-6408-10/regexp.htm


    ===
    Postings such as this are automatically sent once a day. Their
    goal is to answer repeated questions, and to offer the content to
    the community for continuous evaluation/improvement. The complete
    comp.lang.javascript FAQ is at http://www.jibbering.com/faq/.
    The FAQ workers are a group of volunteers.
    FAQ server, Oct 26, 2006
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. FAQ server
    Replies:
    0
    Views:
    134
    FAQ server
    Aug 29, 2006
  2. FAQ server
    Replies:
    6
    Views:
    208
    Jonas Raoni
    Dec 25, 2006
  3. FAQ server
    Replies:
    26
    Views:
    285
    Dr J R Stockton
    Feb 26, 2007
  4. FAQ server
    Replies:
    2
    Views:
    127
    -Lost
    Apr 24, 2007
  5. FAQ server
    Replies:
    0
    Views:
    90
    FAQ server
    Jun 24, 2007
Loading...

Share This Page