469,309 Members | 2,793 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,309 developers. It's quick & easy.

how to use trim() in javascript

18
i used the below code for trimming..

Expand|Select|Wrap|Line Numbers
  1.   var str = "    blah blah   ";
  2.                         var trimmed = str.replace(/^\s+|\s+$/g, '') ;                        
  3.                         alert(trimmed);
  4.                         alert(trimmed.value.length);
its aint working.. i think small error..
can any1 retify..
thanks in advance..
Mar 25 '08 #1
5 17415
aswath
18
i used the bolow example.. none of it is worinking for trimming white spaces

Expand|Select|Wrap|Line Numbers
  1.                        var a = String.trim("        Visit W3Schools ");
  2.                         alert(a)
  3.  
  4.  
  5.                         var sMyVar = new String (" testing trim ");
  6.                         alert(sMyVar.trim());
  7.  
  8.  
  9.                         var str = "    blah blah   ";
  10.                         var trimmed = str.replace(/^\s+|\s+$/g, '') ;                        
  11.                         alert(trimmed);
  12.                         alert(trimmed.value.length);
  13.                         q=str.trim();
  14.                         alert(q);
  15.                         alert("'" + str.trim() + "'");
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)
Mar 25 '08 #2
gits
5,390 Expert Mod 4TB
it works - just use:

Expand|Select|Wrap|Line Numbers
  1. alert(trimmed.length);
kind regards
Mar 25 '08 #3
gits
5,390 Expert Mod 4TB
threads merged - since they cover the same topic ... please don't multipost the same questions ...

kind regards
Mar 25 '08 #4
acoder
16,027 Expert Mod 8TB
Just a note that JavaScript strings don't have a trim() method, though you can add it using String.prototype.
Mar 25 '08 #5
mrhoo
428 256MB
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.

Expand|Select|Wrap|Line Numbers
  1. String.prototype.clean:function(){
  2.     var str= this.replace(/(^\s+)|(\s+$)/g,'');
  3.     return str.replace(/ {2,}/g,' ');
  4. }
Mar 25 '08 #6

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

2 posts views Thread by RobG | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
reply views Thread by harlem98 | last post: by
1 post views Thread by Geralt96 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.