JS 的trim()

时间:2023-03-08 23:20:55
JS 的trim()

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

  • 写成类的方法 :(  str.trim();  )
   <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>
  • 写成函数 :( trim(str); )
 <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>
 <script type="text/javascript">

     var trim = function (str) {//删除左右两端的空格
return str.replace(/(^\s*)|(\s*$)/g, "");
}; //调用示例
if (!trim(regInfo.account)) {
return callback('手机号不能为空!');
}
</script>