js实现trim()方法

在面向对象编程里面去除字符串左右空格是很容易的事,可以使用trim()、ltrim() 或 rtrim(),在jquery里面使用$.trim()也可以轻松的实现。但是在js中却没有这个方法。下面的实现方法用的了正则表达式和replace()方法。

      <script type="text/javascript">  

  function trim(str){ //删除左右两端的空格

       return str.replace(/(^s*)|(s*$)/g, "");  

  }    function ltrim(str){ //删除左边的空格   

     return str.replace(/(^s*)/g,"");  

  }  

  function rtrim(str){ //删除右边的空格    

    return str.replace(/(s*$)/g,"");    }  

 </script>

还可以将trim()方法加入string对象的内置方法中,

     <script language="javascript">  

  String.prototype.trim=function(){

      return this.replace(/(^s*)|(s*$)/g, "");

   }

   String.prototype.ltrim=function(){  

     return this.replace(/(^s*)/g,"");  

  }

   String.prototype.rtrim=function(){  

     return this.replace(/(s*$)/g,"");   

}

  </script>

本文来自:IT蝈蝈开发网

原文地址:https://www.cnblogs.com/wangpf/p/3608800.html