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

Discussion in 'Javascript' started by FAQ server, Feb 22, 2007.

  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/d...html/2380d458-3366-402b-996c-9363906a7353.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://jibbering.com/faq/index.html.
    The FAQ workers are a group of volunteers.
    FAQ server, Feb 22, 2007
    #1
    1. Advertising

  2. FAQ server wrote:
    > -----------------------------------------------------------------------
    > 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,'')")
    >


    What would also be useful is another prototype that reduces multiple
    contiguous spaces to a single space.

    I don't have it at hand but someone here kindly wrote one for me.

    Andrew Poulos
    Andrew Poulos, Feb 22, 2007
    #2
    1. Advertising

  3. FAQ server

    Evertjan. Guest

    Andrew Poulos wrote on 22 feb 2007 in comp.lang.javascript:

    > FAQ server wrote:
    >> -----------------------------------------------------------------------
    >> 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,'')")
    >>

    >
    > What would also be useful is another prototype that reduces multiple
    > contiguous spaces to a single space.


    String.prototype.whiteSpaces2singleSpace =
    new Function("return this.replace(/\\s\\s+/g,' ')")



    --
    Evertjan.
    The Netherlands.
    (Please change the x'es to dots in my emailaddress)
    Evertjan., Feb 22, 2007
    #3
  4. FAQ server

    Une Bévue Guest

    Evertjan. <> wrote:

    > String.prototype.whiteSpaces2singleSpace =
    > new Function("return this.replace(/\\s\\s+/g,' ')")



    writing :

    ....(/\s\s+/g,' ')...

    isn't sufficient no need to escape \ ???

    ami i wrong ?
    --
    Une Bévue
    Une Bévue, Feb 22, 2007
    #4
  5. FAQ server

    Evertjan. Guest

    Une Bévue wrote on 22 feb 2007 in comp.lang.javascript:

    > Evertjan. <> wrote:
    >
    >> String.prototype.whiteSpaces2singleSpace =
    >> new Function("return this.replace(/\\s\\s+/g,' ')")

    >
    >
    > writing :
    >
    > ...(/\s\s+/g,' ')...
    >
    > isn't sufficient no need to escape \ ???
    >
    > ami i wrong ?


    Did you try?

    --
    Evertjan.
    The Netherlands.
    (Please change the x'es to dots in my emailaddress)
    Evertjan., Feb 22, 2007
    #5
  6. FAQ server

    Une Bévue Guest

    Evertjan. <> wrote:

    > Did you try?


    YES here it is :

    <http://www.yvon-thoraval.com/JS/test_regexp.html>

    and i'm TRUE ;-)
    --
    Une Bévue
    Une Bévue, Feb 22, 2007
    #6
  7. FAQ server

    Evertjan. Guest

    Une Bévue wrote on 22 feb 2007 in comp.lang.javascript:

    > Evertjan. <> wrote:
    >
    >> Did you try?

    >
    > YES here it is :
    >
    > <http://www.yvon-thoraval.com/JS/test_regexp.html>


    Nonsense, you did not try,
    but did quite someting else!

    You did this:

    var s = p.replace(/\s\s+/g, ' ');

    While my line was:

    String.prototype.whiteSpaces2singleSpace =
    new Function("return this.replace(/\\s\\s+/g,' ')")

    Please try that with /\\s\\s+/g replaced by /\s\s+/g

    .... and you will see what goes wrong.

    Do you know what goes wrong?

    > and i'm TRUE ;-)


    Are you Boolean?

    --
    Evertjan.
    The Netherlands.
    (Please change the x'es to dots in my emailaddress)
    Evertjan., Feb 22, 2007
    #7
  8. FAQ server

    Une Bévue Guest

    Evertjan. <> wrote:

    > Please try that with /\\s\\s+/g replaced by /\s\s+/g


    i have added the /\\s\\s+/g for t right now

    > Do you know what goes wrong?


    Not at all because i thought the purpose of the Regexp was to replace

    multiple white spaces by single one, as the name :

    String.prototype.whiteSpace2singleSpace implies ???


    --
    Une Bévue
    Une Bévue, Feb 22, 2007
    #8
  9. FAQ server

    Tim Streater Guest

    In article <1htxzrq.n4rk9066racbN%>,
    d (Une Bévue) wrote:

    > Evertjan. <> wrote:
    >
    > > Please try that with /\\s\\s+/g replaced by /\s\s+/g

    >
    > i have added the /\\s\\s+/g for t right now
    >
    > > Do you know what goes wrong?

    >
    > Not at all because i thought the purpose of the Regexp was to replace
    >
    > multiple white spaces by single one, as the name :
    >
    > String.prototype.whiteSpace2singleSpace implies ???


    Safari doesn't like your toolkit.js as there is an extra , on line 348
    or so. FF didn't seem to mind.

    -- tim
    Tim Streater, Feb 22, 2007
    #9
  10. FAQ server

    Evertjan. Guest

    Une Bévue wrote on 22 feb 2007 in comp.lang.javascript:

    > Evertjan. <> wrote:
    >
    >> Please try that with /\\s\\s+/g replaced by /\s\s+/g

    >
    > i have added the /\\s\\s+/g for t right now
    >
    >> Do you know what goes wrong?

    >
    > Not at all because i thought the purpose of the Regexp was to replace
    >
    > multiple white spaces by single one, as the name :
    >
    > String.prototype.whiteSpace2singleSpace implies ???


    You are on the wrong track.

    >> String.prototype.whiteSpaces2singleSpace =
    >> new Function("return this.replace(/\\s\\s+/g,' ')");


    new Function() here has a string as parameter,
    and in javascript strings backslashes are used as escape characters.
    If you need the backslashes, you will have to escape them themselves.
    This is ONLY required in a string,
    not in a regex declaration without a string.

    Try this:

    ====================================
    <script type='text/javascript'>

    alert("return this.replace(/\s\s+/g,' ')");

    alert("return this.replace(/\\s\\s+/g,' ')");

    </script>
    =====================================




    --
    Evertjan.
    The Netherlands.
    (Please change the x'es to dots in my emailaddress)
    Evertjan., Feb 22, 2007
    #10
  11. FAQ server

    Une Bévue Guest

    Evertjan. <> wrote:

    > new Function() here has a string as parameter,
    > and in javascript strings backslashes are used as escape characters.
    > If you need the backslashes, you will have to escape them themselves.
    > This is ONLY required in a string,
    > not in a regex declaration without a string.


    OK, i see what u mean )))

    BUT why did them use :

    String.prototype.toSingleWhiteSpace=function(){
    return this.replace(/\s\s+/g,' ');
    }

    i don'undetstand why u (them) are passing a constant as an argument ???
    --
    Une Bévue
    Une Bévue, Feb 22, 2007
    #11
  12. FAQ server

    Une Bévue Guest

    Tim Streater <> wrote:

    >
    > Safari doesn't like your toolkit.js as there is an extra , on line 348
    > or so. FF didn't seem to mind.


    Fine, thanks, repaired ))

    i let the last "," in order not to forget it when cut'n paste )))


    --
    Une Bévue
    Une Bévue, Feb 22, 2007
    #12
  13. FAQ server

    Evertjan. Guest

    Une Bévue wrote on 22 feb 2007 in comp.lang.javascript:

    > Evertjan. <> wrote:
    >
    >> new Function() here has a string as parameter,
    >> and in javascript strings backslashes are used as escape characters.
    >> If you need the backslashes, you will have to escape them themselves.
    >> This is ONLY required in a string,
    >> not in a regex declaration without a string.

    >
    > OK, i see what u mean )))
    >
    > BUT why did them use :
    >
    > String.prototype.toSingleWhiteSpace=function(){
    > return this.replace(/\s\s+/g,' ');
    >}
    >
    > i don'undetstand why u (them) are passing a constant as an argument ???


    No, it is called a string litteral, javascript has no constants.

    I don't know why, both work.

    --
    Evertjan.
    The Netherlands.
    (Please change the x'es to dots in my emailaddress)
    Evertjan., Feb 22, 2007
    #13
  14. FAQ server

    Une Bévue Guest

    Evertjan. <> wrote:

    > No, it is called a string litteral, javascript has no constants.


    Ok. However a string litteral which doesn't vary ))

    > I don't know why, both work.


    i never used that kind of syntax for a function :

    new Function("what u want to be done");

    i did a little experiment like that :

    String.prototype.hello= new Function("alert('Hello World!')");
    "".hello();

    and it works fine !
    --
    Une Bévue
    Une Bévue, Feb 22, 2007
    #14
  15. On Feb 21, 8:15 pm, Andrew Poulos <> wrote:
    > FAQ server wrote:
    > > -----------------------------------------------------------------------
    > > 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,'')")

    >
    > What would also be useful is another prototype that reduces multiple
    > contiguous spaces to a single space.


    So, am I the only one who finds this syntax horrible to look at?
    Isn't this easier?

    // converted to camelCase to match every other member function in
    Javascript.
    String.prototype.lTrim=function () { return this.replace(/^\s
    +/,''); };
    String.prototype.rTrim=function () { return this.replace(/\s+
    $/,''); };
    String.prototype.trim= function () { return this.replace(/^\s+|\s+$/
    g,''); };

    String.prototype.singleSpace= function () { return this.replace(/\s\s+/
    g,' '); };

    What's the advantage of using
    new Function( 'blah blah blah' )
    instead of
    function () { blah blah blah }
    besides increasing the risk of errors due to unescaped characters?

    In my opinion, as a general rule, eval is evil. The same goes for all
    the other cases where a string literal is executed as code.
    They open up the door for simple errors that are tricky to catch. The
    browsers that required these approaches are all but extinct, and new
    systems tend to implement the native function object approach. If
    there is any other way to get the job done, it's probably best to
    avoid executing a string as code.

    --
    Isaac Z. Schlueter
    http://isaacschlueter.com
    Isaac Schlueter, Feb 23, 2007
    #15
  16. FAQ server

    Evertjan. Guest

    Isaac Schlueter wrote on 23 feb 2007 in comp.lang.javascript:

    > On Feb 21, 8:15 pm, Andrew Poulos <> wrote:
    >>
    >> What would also be useful is another prototype that reduces multiple
    >> contiguous spaces to a single space.

    >
    > So, am I the only one who finds this syntax horrible to look at?
    > Isn't this easier?
    >
    > // converted to camelCase to match every other member function in
    > Javascript.
    > String.prototype.lTrim=function () { return this.replace(/^\s
    > +/,''); };
    > String.prototype.rTrim=function () { return this.replace(/\s+
    > $/,''); };
    > String.prototype.trim= function () { return this.replace(/^\s+|\s+$/
    > g,''); };
    >
    > String.prototype.singleSpace= function () { return
    > this.replace(/\s\s+/ g,' '); };


    I think you are right on both accounts,
    the lowercase naming and the eventual evil eval-ness.

    >
    > What's the advantage of using
    > new Function( 'blah blah blah' )
    > instead of
    > function () { blah blah blah }
    > besides increasing the risk of errors due to unescaped characters?


    The only advantage could be dynamic defining by manipulation of the
    defining string, but even here, you can easily do without:

    function makeTrimProto(name,rgx){
    String.prototype[name] = function ()
    { return this.replace(rgx,' '); };
    };

    makeTrimProto('lTrim', /^\s+/);
    makeTrimProto('rTrim', /\s+$/);
    makeTrimProto('trim', /^\s+|\s+$/g);
    makeTrimProto('singleSpace', /\s\s+/g);

    > In my opinion, as a general rule, eval is evil.

    [..]

    --
    Evertjan.
    The Netherlands.
    (Please change the x'es to dots in my emailaddress)
    Evertjan., Feb 23, 2007
    #16
  17. On Feb 23, 8:40 am, "Evertjan." <> wrote:
    > Isaac Schlueter wrote on 23 feb 2007 in comp.lang.javascript:

    <snip>
    >> What's the advantage of using
    >> new Function( 'blah blah blah' )
    >> instead of
    >> function () { blah blah blah }
    >> besides increasing the risk of errors due to unescaped characters?

    >
    > The only advantage could be dynamic defining by manipulation of the
    > defining string, but even here, you can easily do without:

    <snip>

    That is not the only reason (and it easily could be argued that it is
    not a good idea to be dynamically manipulating script code on the
    client, it certainly introduces an additional layer of issues that
    probably should be avoided). The other good reason for using the
    Function constructor is to create function objects that have a minimum
    scope chain from a context that would impose a more involved scope
    chain on any inner functions created within it.

    <FAQENTRY>Randy, these trim function examples probably are candidates
    for moving away from function constructor use to the use of function
    expressions. Because they are - String.prototype - extensions we can
    be pretty sure they will be evaluated in the global execution context
    and so the scope chains of the functions will not differ depending on
    the creation method, and by now we must be past the point where
    continuing to accommodate browsers that did not understand function
    expressions (pre-IE4, Netscape 4) is pointless.</FAQENTRY>

    Richard.
    Richard Cornford, Feb 23, 2007
    #17
  18. In comp.lang.javascript message <
    glegroups.com>, Fri, 23 Feb 2007 02:51:36, Richard Cornford
    <> posted:
    >by now we must be past the point where
    >continuing to accommodate browsers that did not understand


    <FAQENTRY>

    IMHO, the FAQ should contain a statement along the general lines of

    "In general, the code in this FAQ is for MSIE 4, Netscape 5, Opera 6,
    Firefox 7, and equivalent or later browsers. Much of it will work on
    older systems. Where code will not work on those above, or is present
    specifically to support earlier browsers, that will be noted in or by
    the code."

    If a draft subsection for that is posted here, with a list of the places
    where such markings are known to be needed, then discussion should
    quickly enough yield a generally-acceptable list of browsers and places
    to be marked.

    Consider also, though, javascript in non-browsers.

    --
    (c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Delphi 3? Turnpike 6.05
    <URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/&c., FAQqy topics & links;
    <URL:http://www.bancoems.com/CompLangPascalDelphiMisc-MiniFAQ.htm> clpdmFAQ;
    <URL:http://www.borland.com/newsgroups/guide.html> news:borland.* Guidelines
    Dr J R Stockton, Feb 23, 2007
    #18
  19. FAQ server

    Randy Webb Guest

    Richard Cornford said the following on 2/23/2007 5:51 AM:



    > <FAQENTRY>Randy, these trim function examples probably are candidates
    > for moving away from function constructor use to the use of function
    > expressions.


    The code that I now have locally is this:

    String.prototype.LTrim=function(){return this.replace(/^\s+/,'')}
    String.prototype.RTrim=function(){return this.replace(/\s+$/,'')}
    String.prototype.Trim=function(){return this.replace(/^\s+|\s+$/g,'')}

    If there are not problems/errors with it I will get it uploaded.

    The Number.toFixed entry and the DynWrite entries also use new Function.

    I will work on those two tonight and tomorrow (to do some testing) and
    post the proposed changes to the code for review.

    --
    Randy
    Chance Favors The Prepared Mind
    comp.lang.javascript FAQ - http://jibbering.com/faq/index.html
    Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
    Randy Webb, Feb 24, 2007
    #19
  20. In comp.lang.javascript message <>,
    Sat, 24 Feb 2007 14:50:51, Randy Webb <> posted:
    >The code that I now have locally is this:
    >
    >String.prototype.LTrim=function(){return this.replace(/^\s+/,'')}
    >String.prototype.RTrim=function(){return this.replace(/\s+$/,'')}
    >String.prototype.Trim=function(){return this.replace(/^\s+|\s+$/g,'')}


    Others have already asked you to make better use of whitespace in FAQ
    code.


    String.prototype.LTrim =
    function() { return this.replace(/^\s+/, "") }
    String.prototype.RTrim =
    function() { return this.replace(/\s+$/, "") }
    String.prototype.Trim =
    function() { return this.replace(/^\s+|\s+$/g, "") }


    --
    (c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Delphi 3? Turnpike 6.05
    <URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/&c., FAQqy topics & links;
    <URL:http://www.bancoems.com/CompLangPascalDelphiMisc-MiniFAQ.htm> clpdmFAQ;
    <URL:http://www.borland.com/newsgroups/guide.html> news:borland.* Guidelines
    Dr J R Stockton, Feb 25, 2007
    #20
    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:
    133
    FAQ server
    Aug 29, 2006
  2. FAQ server
    Replies:
    0
    Views:
    128
    FAQ server
    Oct 26, 2006
  3. FAQ server
    Replies:
    6
    Views:
    206
    Jonas Raoni
    Dec 25, 2006
  4. FAQ server
    Replies:
    2
    Views:
    125
    -Lost
    Apr 24, 2007
  5. FAQ server
    Replies:
    0
    Views:
    89
    FAQ server
    Jun 24, 2007
Loading...

Share This Page