关于JS中字符串去空格的解决方法

来源:互联网 发布:宏程序 刀具寿命 编程 编辑:程序博客网 时间:2024/05/21 10:06

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

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

Code:
  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.   
  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>   

     整理 by  Janrone  、 我的个人主页:http://student.csdn.net/?111103

    加我为好友  希望和大家共同学习。

原创粉丝点击