How can I trim the sides of a string?

Discussion in 'Javascript' started by Reply Via Newsgroup, Apr 5, 2004.

  1. Folks,

    In PHP and some other scripting languages, one has trim() - It removes
    newline, tabs and blank spaces that might prefix, or suffix a string.

    Can someone tell me how I can do this in javascript?

    Much appreciated,
    randell d.
    Reply Via Newsgroup, Apr 5, 2004
    #1
    1. Advertising

  2. Reply Via Newsgroup wrote:
    > In PHP and some other scripting languages, one has trim() - It removes
    > newline, tabs and blank spaces that might prefix, or suffix a string.
    >
    > Can someone tell me how I can do this in javascript?
    >


    http://jibbering.com/faq/#FAQ4_16


    JW
    Janwillem Borleffs, Apr 5, 2004
    #2
    1. Advertising

  3. Reply Via Newsgroup

    pcx99 Guest

    Reply Via Newsgroup wrote:
    >
    > Folks,
    >
    > In PHP and some other scripting languages, one has trim() - It removes
    > newline, tabs and blank spaces that might prefix, or suffix a string.
    >
    > Can someone tell me how I can do this in javascript?
    >
    > Much appreciated,
    > randell d.



    http://www.vermontsoftware.com/Javascript/trim.html
    pcx99, May 1, 2004
    #3
  4. Reply Via Newsgroup

    Fox Guest

    pcx99 wrote:
    >
    > Reply Via Newsgroup wrote:
    > >
    > > Folks,
    > >
    > > In PHP and some other scripting languages, one has trim() - It removes
    > > newline, tabs and blank spaces that might prefix, or suffix a string.
    > >
    > > Can someone tell me how I can do this in javascript?
    > >
    > > Much appreciated,
    > > randell d.

    >
    > http://www.vermontsoftware.com/Javascript/trim.html



    String.prototype.trim = function()
    {
    return this.match(/(\b\S+|\S+)/g).join(" ");
    }
    Fox, May 2, 2004
    #4
  5. On Sun, 02 May 2004 07:03:20 -0500, Fox <> wrote:

    [snip]

    > String.prototype.trim = function()
    > {
    > return this.match(/(\b\S+|\S+)/g).join(" ");
    > }


    The FAQ version seems to be more logical.

    Mike

    --
    Michael Winter
    d (replace ".invalid" with ".uk" to reply)
    Michael Winter, May 2, 2004
    #5
  6. JRS: In article <>, seen in
    news:comp.lang.javascript, Michael Winter <
    d> posted at Sun, 2 May 2004 15:52:03 :
    >On Sun, 02 May 2004 07:03:20 -0500, Fox <> wrote:
    >
    >[snip]
    >
    >> String.prototype.trim = function()
    >> {
    >> return this.match(/(\b\S+|\S+)/g).join(" ");
    >> }

    >
    >The FAQ version seems to be more logical.


    More importantly, it does what "randell d." asked for, whereas the
    quoted code also converts multiple spaces within the string to singles.

    That task can, AFAICS, be done by S.split(/\s+/).join(" "); and that
    task might be worth including in the FAQ section, with optimum solution.

    --
    © John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
    <URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
    <URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
    <URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
    Dr John Stockton, May 4, 2004
    #6
  7. Reply Via Newsgroup

    rh Guest

    Dr John Stockton <> wrote in message news:<>...
    > JRS: In article <>, seen in
    > news:comp.lang.javascript, Michael Winter <
    > d> posted at Sun, 2 May 2004 15:52:03 :
    > >On Sun, 02 May 2004 07:03:20 -0500, Fox <> wrote:
    > >
    > >[snip]
    > >
    > >> String.prototype.trim = function()
    > >> {
    > >> return this.match(/(\b\S+|\S+)/g).join(" ");
    > >> }

    > >
    > >The FAQ version seems to be more logical.

    >
    > More importantly, it does what "randell d." asked for, whereas the
    > quoted code also converts multiple spaces within the string to singles.
    >
    > That task can, AFAICS, be done by S.split(/\s+/).join(" "); and that
    > task might be worth including in the FAQ section, with optimum solution.


    The FAQ version is clearly the correct way to trim strings. However,
    I'm curious as to the reason the FAQ prototype is generated with "new
    Function(str)" instead of the more common function-expression form
    given above.

    Strings introduce the requirement for double escaping the "\" (as per
    new RegExp), and while such use may be instructive, it adds
    chicken-track complexity where in a place where it doesn't appear to
    be necessary.

    Am I missing some subletly regarding browser compatibility, or
    something to do with "this" association?

    ../rh
    rh, May 5, 2004
    #7
  8. Reply Via Newsgroup

    Shawn Milo Guest

    Reply Via Newsgroup <> wrote in message news:<FMjcc.30509$Pk3.9550@pd7tw1no>...
    > Folks,
    >
    > In PHP and some other scripting languages, one has trim() - It removes
    > newline, tabs and blank spaces that might prefix, or suffix a string.
    >
    > Can someone tell me how I can do this in javascript?
    >
    > Much appreciated,
    > randell d.


    There is a quick, easy way to do this with a regular expression.
    It only takes one line of Javascript.

    Code written, commented, and tested by me. No warranty. :eek:)

    Shawn




    <script type="text/javascript">


    var testString = ' there are leading and trailing spaces (and tabs) ';

    alert('\'' + testString + '\'');


    //regex explanation:
    //regex is in forward slashes: //
    // syntax string = string.replace(/pattern/, 'replace with this');

    ^ = beginning of line
    (\s+)? = one or more characters of whitespace, optional
    (.*\S) = any characters, with the last one not being whitespace
    (\s+)? = one or more characters of whitespace, optional
    $ = end of line
    $2 = what was in the 2nd set of parenthesis

    testString = testString.replace(/^(\s+)?(.*\S)(\s+)?$/, '$2');

    alert('\'' + testString + '\'');

    </script>
    Shawn Milo, May 5, 2004
    #8
  9. rh wrote:

    >>> Fox <> wrote:
    >>>> [...]
    >>>> String.prototype.trim = function()
    >>>> {
    >>>> return this.match(/(\b\S+|\S+)/g).join(" ");
    >>>> }

    >
    > The FAQ version is clearly the correct way to trim strings. However,
    > I'm curious as to the reason the FAQ prototype is generated with "new
    > Function(str)" instead of the more common function-expression form
    > given above.
    >
    > Strings introduce the requirement for double escaping the "\" (as per
    > new RegExp), and while such use may be instructive, it adds
    > chicken-track complexity where in a place where it doesn't appear to
    > be necessary.


    Depends.

    > Am I missing some subletly regarding browser compatibility,


    Yes, indeed you do. If Netscape's Core JavaScript Reference 1.5 and the
    MSDN Library is to be trusted, the Function() constructor is available from
    JavaScript 1.1 (NN3+) and JScript 2.0 (IE/IIS 3+) on, while the "function"
    statement within another statement (including itself) or the "function"
    operator (also defining anonymous functions) requires JavaScript 1.2 (NN4+)
    or 1.5 (NN6+; in JScript AFAIS both are available in all versions and thus
    all UAs), respectively. (Unfortunately, the Reference cannot be trusted
    here since I had to learn that NN 4.7 which claims to support JavaScript
    up to 1.3 only also supports the "function" operator.)

    As for the ECMAScript standard, the "function" statement within a
    statement is AFAIS not available before edition 3 as there is no
    FunctionExpression to be produceable through the MemberExpression production.

    While the UAs given respect to herewith may seem outdated, there may
    be still UAs around which implement only those older versions of the
    respective language(s). However, we also had one case of a buggy
    implementation here that had b0rken Function() constructor support.
    Google is your friend. [psf 6.1]

    <http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/function.html#1193137>
    <http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/stmt.html#1004825>
    <http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/ops.html#1066344>
    <http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/js56jsoriVersionInformation.asp>

    > or something to do with "this" association?


    No.

    String.prototype.trim = new Function(
    "return this.match(/(\\b\\S+|\\S+)/g).join(' ');");

    is semantically equal to the above.


    HTH

    PointedEars
    Thomas 'PointedEars' Lahn, May 6, 2004
    #9
  10. Reply Via Newsgroup

    Jon Kelling Guest

    for all your javascript trimming needs...

    function trim(inputString) {
    if (typeof inputString != "string") return inputString;
    return inputString
    //clear leading spaces and empty lines
    .replace(/^(\s|\n|\r)*((.|\n|\r)*?)(\s|\n|\r)*$/g,"$2")

    //take consecutive spaces down to one
    .replace(/(\s(?!(\n|\r))(?=\s))+/g,"")

    //take consecutive lines breaks down to one
    .replace(/(\n|\r)+/g,"\n\r")

    //remove spacing at the beginning of a line
    .replace(/(\n|\r)\s/g,"$1")

    //remove spacing at the end of a line
    .replace(/\s(\n|\r)/g,"$1");
    }

    -- Jon

    pcx99 <> wrote in message news:<egVkc.5975$>...
    > Reply Via Newsgroup wrote:
    > >
    > > Folks,
    > >
    > > In PHP and some other scripting languages, one has trim() - It removes
    > > newline, tabs and blank spaces that might prefix, or suffix a string.
    > >
    > > Can someone tell me how I can do this in javascript?
    > >
    > > Much appreciated,
    > > randell d.

    >
    >
    > http://www.vermontsoftware.com/Javascript/trim.html
    Jon Kelling, May 6, 2004
    #10
  11. Reply Via Newsgroup

    bruce Guest

    function TrimSpacesFromBeginAndEnd (str)
    {
    pattern1=/[\s]+$/
    pattern2=/^[\s]+/
    y=str.replace(pattern2,"").replace(pattern1,"")
    return y
    }


    This is assuming no unprintable characters...
    bruce, May 6, 2004
    #11
  12. Reply Via Newsgroup

    rh Guest

    Thomas 'PointedEars' Lahn <> wrote in message news:<>...
    > rh wrote:
    >
    > >>> Fox <> wrote:
    > >>>> [...]
    > >>>> String.prototype.trim = function()
    > >>>> {
    > >>>> return this.match(/(\b\S+|\S+)/g).join(" ");
    > >>>> }

    > >
    > > The FAQ version is clearly the correct way to trim strings. However,
    > > I'm curious as to the reason the FAQ prototype is generated with "new
    > > Function(str)" instead of the more common function-expression form
    > > given above.
    > >
    > > Strings introduce the requirement for double escaping the "\" (as per
    > > new RegExp), and while such use may be instructive, it adds
    > > chicken-track complexity where in a place where it doesn't appear to
    > > be necessary.

    >
    > Depends.
    >
    > > Am I missing some subletly regarding browser compatibility,

    >
    > Yes, indeed you do. If Netscape's Core JavaScript Reference 1.5 and the
    > MSDN Library is to be trusted, the Function() constructor is available from
    > JavaScript 1.1 (NN3+) and JScript 2.0 (IE/IIS 3+) on, while the "function"
    > statement within another statement (including itself) or the "function"
    > operator (also defining anonymous functions) requires JavaScript 1.2 (NN4+)
    > or 1.5 (NN6+; in JScript AFAIS both are available in all versions and thus
    > all UAs), respectively. (Unfortunately, the Reference cannot be trusted
    > here since I had to learn that NN 4.7 which claims to support JavaScript
    > up to 1.3 only also supports the "function" operator.)
    >
    > As for the ECMAScript standard, the "function" statement within a
    > statement is AFAIS not available before edition 3 as there is no
    > FunctionExpression to be produceable through the MemberExpression production.
    >
    > While the UAs given respect to herewith may seem outdated, there may
    > be still UAs around which implement only those older versions of the
    > respective language(s). However, we also had one case of a buggy
    > implementation here that had b0rken Function() constructor support.
    > Google is your friend. [psf 6.1]
    >
    > <http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/function.html#1193137>
    > <http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/stmt.html#1004825>
    > <http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/ops.html#1066344>
    > <http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/js56jsoriVersionInformation.asp>
    >
    > > or something to do with "this" association?

    >
    > No.
    >
    > String.prototype.trim = new Function(
    > "return this.match(/(\\b\\S+|\\S+)/g).join(' ');");
    >
    > is semantically equal to the above.
    >
    >
    > HTH


    It does, thanks for taking the time to lay it out.

    (I'm glad to see you got by my misspelling of subtlety above. Now if
    we can just get you to use "broken" instead of "borken" and "b0rken"
    -- or is this another psf-ism? :))

    ../rh
    >
    > PointedEars
    rh, May 7, 2004
    #12
    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:
    138
    FAQ server
    Aug 29, 2006
  2. FAQ server
    Replies:
    0
    Views:
    135
    FAQ server
    Oct 26, 2006
  3. FAQ server
    Replies:
    6
    Views:
    213
    Jonas Raoni
    Dec 25, 2006
  4. FAQ server
    Replies:
    26
    Views:
    293
    Dr J R Stockton
    Feb 26, 2007
  5. FAQ server
    Replies:
    2
    Views:
    130
    -Lost
    Apr 24, 2007
Loading...

Share This Page