JS 的trim()

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

 

  • 写成类的方法 :(  str.trim();  )
 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>
View Code
  • 写成函数 :( trim(str); )
 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>
View Code

 

 1 <script type="text/javascript">
 2 
 3     var trim = function (str) {//删除左右两端的空格
 4         return str.replace(/(^s*)|(s*$)/g, "");
 5     };
 6 
 7       //调用示例
 8     if (!trim(regInfo.account)) {
 9             return callback('手机号不能为空!');
10     }
11 </script>
View Code

 

原文地址:https://www.cnblogs.com/Sisiflying/p/5439836.html