//去除空格 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, ""); } “测试 ”.Trim();
数组去重
var arr=["a","b","c","a","ba","bc"];
alert(arr.join(",").match( /([^,]+)(?!.*,\1(,|$))/ig));
//下面方法没有缺陷,上面方法有问题
var str="36,35,26,41,42,36,36,35,41,25,26,";var ret = [];var re = str.split(',');str.replace(/[^,]+/g, function($0, $1) { (str.indexOf($0) == $1) && ret.push($0)})alert(ret)
切换(隐藏/显示) 两个元素切换: 把两个元素放到一个div中,则它们的索引为:0,1 index:要显示的那个元素 var hideIndex = parseInt((index+2)/2-index);//隐藏的那个元素 三个元素切换: index:要显示的那个元素 var hideIndex = parseInt((index+2)/2-index);//第一个隐藏的那个元素 var hideIndex2 = hideIndex+1; Math.ceil(hideIndex2);//上舍 第二个隐藏的元素 hideIndex2.toFixed(0);//四舍五入 第二个隐藏的元素 Math.round(hideIndex2);//四舍五入 第二个隐藏的元素 Math.floor(hideIndex2);//下舍
//数组搜索元素 Array.prototype.indexOf=function(substr,start){ var ta,rt,d='\0'; if(start!=null){ta=this.slice(start);rt=start;}else{ta=this;rt=0;} var str=d+ta.join(d)+d,t=str.indexOf(d+substr+d); if(t==-1)return -1;rt+=str.slice(0,t).replace(/[^\0]/g,'').length; return rt; } Array.prototype.lastIndexOf=function(substr,start){ var ta,rt,d='\0'; if(start!=null){ta=this.slice(start);rt=start;}else{ta=this;rt=0;} ta=ta.reverse();var str=d+ta.join(d)+d,t=str.indexOf(d+substr+d); if(t==-1)return -1;rt+=str.slice(t).replace(/[^\0]/g,'').length-2; return rt; } Array.prototype.replace=function(reg,rpby){ var ta=this.slice(0),d='\0'; var str=ta.join(d);str=str.replace(reg,rpby); return str.split(d); } Array.prototype.search=function(reg){ var ta=this.slice(0),d='\0',str=d+ta.join(d)+d,regstr=reg.toString(); reg=new RegExp(regstr.replace(/\/((.|\n)+)\/.*/g,'\\0$1\\0'),regstr.slice(regstr.lastIndexOf('/')+1)); t=str.search(reg);if(t==-1)return -1;return str.slice(0,t).replace(/[^\0]/g,'').length; } window.onload=function(){ var a=new Array('aa1321321','b4323424b','cc345345','dd4654','dd4654','b4323424b'); document.getElementById('t1').value=a.toString(); document.getElementById('t2').value=a.indexOf('cc345345'); document.getElementById('t3').value=a.lastIndexOf('dd4654'); document.getElementById('t4').value=a.replace(/\d/g,'*'); document.getElementById('t5').value=a.search(/dd4654/); };
//js中导入js文件 1、 document.write("<script language='javascript' src='string.js' ></script>"); 2、 function insertJS(src, callback){ var script = document.createElement("SCRIPT"), done = false; script.type = "text/javascript"; script.src = src; script.charset = "GB2312"; script.onload = script.onreadystatechange = function(){ if ( !done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") ) { done = true; } }; document.getElementsByTagName("HEAD")[0].appendChild(script);} insertJS("1.js")