zoukankan      html  css  js  c++  java
  • js 去空格函数与正则

    如果项目没有用到jQuery等框架的话,js本身又没有这样的函数,我们不得不自己写这样的函数,下面是函数的具体实现:

    //
    供使用者调用 function trim(s){ return trimRight(trimLeft(s)); } //去掉左边的空白 function trimLeft(s){ if(s == null) { return ""; } var whitespace = new String(" "); var str = new String(s); if (whitespace.indexOf(str.charAt(0)) != -1) { var j=0, i = str.length; while (j < i && whitespace.indexOf(str.charAt(j)) != -1){ j++; } str = str.substring(j, i); } return str; } //去掉右边的空白 function trimRight(s){ if(s == null) return ""; var whitespace = new String(" "); var str = new String(s); if (whitespace.indexOf(str.charAt(str.length-1)) != -1){ var i = str.length - 1; while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1){ i--; } str = str.substring(0, i+1); } return str; }

    <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> 
    <input type="text" value="    前后都是空格   " id="space"> 
    <input type="button" value="去前后空格" onclick="javascript:document.getElementById('space').value=document.getElementById('space').value.Trim();document.getElementById('space').select();"> 
    <input type="button" value="去前空格" onclick="javascript:document.getElementById('space').value=document.getElementById('space').value.LTrim();document.getElementById('space').select();"> 
    <input type="button" value="去后空格" onclick="javascript:document.getElementById('space').value=document.getElementById('space').value.RTrim();document.getElementById('space').select();"> 
    <input type="button" value="还原" onclick="javascript:document.getElementById('space').value='    前后都是空格     ';"> 
    
    
    

      




  • 相关阅读:
    org.hibernate.NonUniqueObjectException 原因及解决办法
    Hibernate方法save、update、merge、saveOrUpdate及get和load的区别
    Hibernate实体对象的生命周期(三种状态)
    Java I/O 全面详解
    故障检测、性能调优与Java类加载机制
    Linux基本命令+Makefile
    Redhat9.0+Apache1.3.29+Mysql3.23.58+PHP4.3.4
    u盘安装Linux系统详细教程
    Linux下软件常见安装方式
    Spring MVC 小计
  • 原文地址:https://www.cnblogs.com/ShanHeDiao/p/4524057.html
Copyright © 2011-2022 走看看