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='    前后都是空格     ';"> 
    
    
    

      




  • 相关阅读:
    3n+1问题
    判断x的m次方和y的m次方末尾三位数是否相等
    OpenJudge 计算概论1007:点评赛车
    整数划分问题【转】
    证明:平面内有5个整点,必有两个点连线的中点为整点【本资源整理自网络】
    欧几里德算法的证明
    导出本地和远程SVN项目, Export remote SVN repository
    Centos7的firewalld配置
    ESXi5.5下的Centos7虚机配置静态IP
    Dubbo消费端错误: ClassNotFoundException: org.apache.zookeeper.proto.WatcherEvent
  • 原文地址:https://www.cnblogs.com/ShanHeDiao/p/4524057.html
Copyright © 2011-2022 走看看