js去掉前后空格

function String.prototype.Trim() { return this.replace(/(^/s*)|(/s*$)/g, ""); }   // 去掉左右空格

      function String.prototype.Ltrim() { return this.replace(/(^/s*)/g, ""); }            // 去掉左空格
      function String.prototype.Rtrim() { return this.replace(/(/s*$)/g, ""); }            // 去掉右空格

        eg.

        

[javascript] view plain copy
 
  1. function getDDLValueForSelected(row) {  
  2.   
  3.             // 设置选中行后,下拉菜单显示选中的值  
  4.   
  5.             if (G('ctl00_ddl01').disabled == "") { // 下拉菜单为启用状态  
  6.   
  7.                 if (row.cells(7).innerText != "") {  
  8.   
  9.                     for (var i = 0; i < G('ctl00_ddl01').options.length; i++) {  
  10.   
  11.                         if (textTrim(G('ctl00_ddl01').options[i].text) == textTrim(row.cells(1).innerText)) {  
  12.   
  13.                             G('ctl00_ddl01').selectedIndex = i;  
  14.   
  15.                         }  
  16.   
  17.                     }  
  18.   
  19.                     for (var j = 0; j < G('ctl00_ddl02').options.length; j++) {  
  20.   
  21.                         if (textTrim(G('ctl00_ddl02').options[j].text) == textTrim(row.cells(2).innerText)) {  
  22.   
  23.                             G('ctl00_ddlInterface').selectedIndex = j;  
  24.   
  25.                         }  
  26.   
  27.                     }  
  28.   
  29.                 }  
  30.   
  31.             }  
  32.   
  33.         }  
  34.   
  35.    
  36.   
  37.   
  38.   
  39.         function textTrim(txt) {  
  40.   
  41.             return txt.replace(/(^/s*)|(/s*$)/g, "");  
  42.   
  43.         }  


 

 ------------------------------

   去除字符串左右两端的空格,在vbscript里面可以轻松地使用 trim、ltrim 或 rtrim,但在js中却没有这3个内置方法,需要手工编写。下面的实现方法是用到了正则表达式,效率不错,并把这三个方法加入String对象的内置方法中去。


  写成类的方法格式如下:(str.trim();)


  

[javascript] view plain copy
 
  1. <script language="javascript">  
  2.    String.prototype.trim=function(){  
  3.       return this.replace(/(^s*)|(s*$)/g, "");  
  4.    }  
  5.    String.prototype.ltrim=function(){  
  6.       return this.replace(/(^s*)/g,"");  
  7.    }  
  8.    String.prototype.rtrim=function(){  
  9.       return this.replace(/(s*$)/g,"");  
  10.    }  
  11.   </script>  


  写成函数可以这样:(trim(str))
  

[javascript] view plain copy
 
    1. <script type="text/javascript">  
    2.    function trim(str){ //删除左右两端的空格  
    3.        return str.replace(/(^s*)|(s*$)/g, "");  
    4.    }  
    5.    function ltrim(str){ //删除左边的空格  
    6.        return str.replace(/(^s*)/g,"");  
    7.    }  
    8.    function rtrim(str){ //删除右边的空格  
    9.        return str.replace(/(s*$)/g,"");  
    10.    }  
    11.   </script>  
原文地址:https://www.cnblogs.com/shiyh/p/7146466.html