zoukankan      html  css  js  c++  java
  • 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

     

  • 相关阅读:
    JAVA 导包,使用前面的类~
    JAVA 类的定义(定义一个类,来模拟“学生”)
    Python 猜数游戏
    JAVA 数组作为方法参数—传递地址
    JAVA 数组作为方法返回值—返回地址
    JAVA 求数组中的最大值
    JAVA 数组元素的反转
    07-递归案例
    05-函数是一种类型
    06-递归
  • 原文地址:https://www.cnblogs.com/Sisiflying/p/5439836.html
Copyright © 2011-2022 走看看