首页 > Web开发 > 详细

用javascript去掉字符串空格的办法

时间:2014-01-28 00:38:13      阅读:384      评论:0      收藏:0      [点我收藏+]

今天遇到了以关于JavaScript 中怎么去掉 字符串中前后两段的空格 ,我只好向就得js中也后Trim() 函数,后来试试了不

行,就网上找了下解决方法,其中用到了正则表达式 ,整理了下:

bubuko.com,布布扣
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   
 2 <html xmlns="http://www.w3.org/1999/xhtml">   
 3 <head>   
 4 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />   
 5 <title>测试去空格</title>   
 6 <script language="javascript" type="text/javascript">   
 7     //http://www.cnblogs.com/roucheng/
 8     //Trim()   ,   Ltrim()   ,   RTrim()   函数 
 9   String.prototype.Trim   =   function()      
10   {      
11   return   this.replace(/(^/s*)|(/s*$)/g,   "");      
12   }      
13        
14   String.prototype.LTrim   =   function()      
15   {      
16   return   this.replace(/(^/s*)/g,   "");      
17   }      
18        
19   String.prototype.RTrim   =   function()      
20   {      
21   return   this.replace(/(/s*$)/g,   "");      
22   }        
23        
24    function testTrim()   
25  {   
26     //alert("用户明不能为空!");   
27     var name=document.myform.uname.value.Trim();   
28     if(name.length==0){   
29     alert("用户明不能为空!"+name.length);   
30     document.myform.uname.select();   
31     return false;   
32     }   
33  }   
34   
35 </script>   
36 </head>   
37   
38 <body>   
39 <form id="myform" name="myform" method="post" action="">   
40   <label>   
41   <input type="text" name="uname" />   
42   </label>   
43   <label>   
44   <input type="submit" name="Submit" value="提交" onclick="return testTrim()" />   
45   </label>   
46 </form>   
47 </body>   
48 </html>
bubuko.com,布布扣

 http://www.cnblogs.com/roucheng/

用javascript去掉字符串空格的办法

原文:http://www.cnblogs.com/roucheng/p/3535223.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!