how to use trim() in javascript

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aswath
    New Member
    • Mar 2008
    • 18

    how to use trim() in javascript

    i used the below code for trimming..

    [CODE=javascript] var str = " blah blah ";
    var trimmed = str.replace(/^\s+|\s+$/g, '') ;
    alert(trimmed);
    alert(trimmed.v alue.length);[/CODE]

    its aint working.. i think small error..
    can any1 retify..
    thanks in advance..
    Last edited by gits; Mar 25 '08, 09:07 AM. Reason: added code tags
  • aswath
    New Member
    • Mar 2008
    • 18

    #2
    how to use trim() in javascript

    i used the bolow example.. none of it is worinking for trimming white spaces

    [CODE=javascript] var a = String.trim(" Visit W3Schools ");
    alert(a)


    var sMyVar = new String (" testing trim ");
    alert(sMyVar.tr im());


    var str = " blah blah ";
    var trimmed = str.replace(/^\s+|\s+$/g, '') ;
    alert(trimmed);
    alert(trimmed.v alue.length);
    q=str.trim();
    alert(q);
    alert("'" + str.trim() + "'");[/CODE]

    all my need is to take off white spaces before and after a string but not inbetween a string.. ie.,
    '' babe babe " should be ''babe babe"......

    any help..
    thanks in advance..
    regards.
    aswath.n.s
    (knowledge is power)
    Last edited by gits; Mar 25 '08, 09:07 AM. Reason: added code tags

    Comment

    • gits
      Recognized Expert Moderator Expert
      • May 2007
      • 5390

      #3
      it works - just use:

      [CODE=javascript]alert(trimmed.l ength);[/CODE]
      kind regards

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5390

        #4
        threads merged - since they cover the same topic ... please don't multipost the same questions ...

        kind regards

        Comment

        • acoder
          Recognized Expert MVP
          • Nov 2006
          • 16032

          #5
          Just a note that JavaScript strings don't have a trim() method, though you can add it using String.prototyp e.

          Comment

          • mrhoo
            Contributor
            • Jun 2006
            • 428

            #6
            this method removes leading and trailing whitespace from a string.
            The second replace replaces multiple consecutive spaces (but not tabs or newlines) with single spaces-
            take it out if you don't want that behavior.

            [CODE=javascript]String.prototyp e.clean:functio n(){
            var str= this.replace(/(^\s+)|(\s+$)/g,'');
            return str.replace(/ {2,}/g,' ');
            }[/CODE]

            Comment

            Working...