JavaScript常用字符串与数组扩展函数小结
String对象的扩展函数:
String.prototype.trim=function(){
returnthis.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim=function(){
returnthis.replace(/^\s+/g,"");
}
String.prototype.rtrim=function(){
returnthis.replace(/\s+$/g,"");
}
String.prototype.splitAndTrim=function($delimiter,$limit)
{
var$ss=this.split($delimiter,$limit);
for(var$i=0;$i<$ss.length;$i++)
$ss[$i]=$ss[$i].trim();
return$ss;
}
String.prototype.htmlEntities=function(){
returnthis.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
String.prototype.stripTags=function(){
returnthis.replace(/<([^>]+)>/g,'');
}
String.prototype.toArray=function(){
returnthis.split('');
}
String.prototype.toIntArray=function(){
varreturnArray=[];
for(vari=0;i<this.length;i++){
returnArray.push(this.charCodeAt(i));
}
returnreturnArray;
}
String.prototype.replaceAll=function($old,$snew){
returnthis.replace(newRegExp($old,"gm"),$snew);
}
变量替换
vara="ILove{0},andYouLove{1},Whereare{0}!";a.format("You","Me");
String.prototype.format=function(){
varargs=arguments;
returnthis.replace(/\{(\d+)\}/g,function(m,i,o,n){
returnargs[i];
});
}
在字符串末尾追加字符串
String.prototype.append=function($str){
returnthis.concat($str);
}
删除指定索引位置的字符,索引无效将不删除任何字符
String.prototype.deleteCharAt=function($sIndex){
if($sIndex<0||$sIndex>=this.length){
returnthis.valueOf();
}elseif($sIndex==0){
returnthis.substring(1,this.length);
}elseif($sIndex==this.length-1){
returnthis.substring(0,this.length-1);
}else{
returnthis.substring(0,$sIndex)+this.substring($sIndex+1);
}
}
删除指定索引间的字符串.$sIndex和$eIndex所在的字符不被删除!依赖deleteCharAt
String.prototype.deleteString=function($sIndex,$eIndex){
if($sIndex==$eIndex){
returnthis.deleteCharAt($sIndex);
}else{
if($sIndex>$eIndex){
vartIndex=$eIndex;
$eIndex=$sIndex;
$sIndex=tIndex;
}
if($sIndex<0)$sIndex=0;
if($eIndex>this.length-1)$eIndex=this.length-1;
returnthis.substring(0,$sIndex+1)+this.substring($eIndex,this.length);
}
}
检查字符串是否以某个字符串(str)结尾
String.prototype.endsWith=function($str){
returnthis.substr(this.length-$str.length)==$str;
}
检查该字符串是否以某个字符串开始
String.prototype.startsWith=function(str){
returnthis.substr(0,str.length)==str;
}
比较两个字符串是否相等,不区分大小写!
String.prototype.equalsIgnoreCase=function($str){
if(this.length!=$str.length){
returnfalse;
}else{
vartmp1=this.toLowerCase();
vartmp2=$str.toLowerCase();
returntmp1==tmp2;
}
}
将指定的字符串插入到指定的位置后面!索引无效将直接追加到字符串的末尾
String.prototype.insert=function($ofset,$str){
if($ofset<0||$ofset>=this.length-1){
returnthis.concat($str);
}
returnthis.substring(0,$ofset)+$str+this.substring($ofset+1);
}
将指定的位置的字符设置为另外指定的字符或字符串.索引无效将直接返回不做任何处理!
String.prototype.setCharAt=function($ofset,$str){
if($ofset<0||$ofset>=this.length-1){
returnthis.valueOf();
}
returnthis.substring(0,$ofset)+$str+this.substring($ofset+1);
}
String.prototype.replaceLen=function(start,len,replaced){
if(!len)
returnthis;
if(start>=this.length)
returnthis;
varreturnSeg='';
varreturnSeg2='';
vari=0;
for(;i<this.length;i++){
varc=this.charAt(i);
if(i<start)
returnSeg+=c;
if(i>=start+len)
returnSeg2+=c;
}
returnreturnSeg+replaced+returnSeg2;
}
扩展基础类:
替换字符,这个在替换填入比较有用,比如***天***小时替换为<input/>天<input/>小时
String.prototype.replaceChar=function(target,replaced,start){
if(!target)
returnthis;
if(!start)
start=0;
varreturnVal=this.substring(0,start);
varindex=0;
for(vari=start;i<this.length;i++){
varc=this.charAt(i);
target=typeoftarget=='function'?target.call(this,index):target;
if(c==target){
returnVal+=typeofreplaced=='function'?replaced.call(this,index):replaced;
while(i<this.length-1&&this.charAt(i+1)==c){
i++;
}
index++;
}else{
returnVal+=c;
}
}
returnreturnVal;
}
将该字符串反序排列
String.prototype.reverse=function(){
varstr="";
for(vari=this.length-1;i>=0;i--){
str=str.concat(this.charAt(i));
}
returnstr;
}
计算长度,每个汉字占两个长度,英文字符每个占一个长度
String.prototype.ucLength=function(){
varlen=0;
for(vari=0;i<this.length;i++){
if(this.charCodeAt(i)>255)len+=2;
elselen++;
}
returnlen;
}
在字符串的左边填充一些特定的字符
String.prototype.lpad=function(len,s){
vara=newArray(this);
varn=(len-this.length);
for(vari=0;i<n;i++){
a.unshift(s);
}
returna.join("");
}
在字符串的右边填充一些特定的字符
String.prototype.rpad=function(len,s){
vara=newArray(this);
varn=(len-this.length);
for(vari=0;i<n;i++){
a.push(s);
}
returna.join("");
}
把字符串的首字母转化为大写
String.prototype.ucwords=function(){
returnthis.substring(0,1).toUpperCase().concat(this.substring(1));
}
String.prototype.contains=function($str){
returnthis.indexOf($str)>-1?true:false;
}
将格式为2008-04-0210:08:44的字符串转成日期(String对象的值必须为:2008-04-0210:08:44)
String.prototype.toDate=function(){
varstr=this.replace(/-/g,"/");
return(newDate(str));
}
将原来用字符串表示的十进数转成十进制浮点数:precision为精度
String.prototype.toFloat=function(precision){
precision=precision||2;
returnparseFloat(this,10).toFixed(precision);
}
将原来用字符串表示的十进数转成十进制整数
String.prototype.toInt=function(){
returnparseInt(this,10).toString();
}
将两个原来用字符串表示的十进数相加后当作字串返回:addend为加数
String.prototype.add=function(addend){
varsum=parseFloat(this,10)+parseFloat(addend,10);
returnsum+"";
}
十进制转其他进制代码如下nextScale为进制如2,8,16
String.prototype.shiftScale=function(nextScale){
returnparseFloat(this).toString(nextScale);
}
各进制互相转换:
this对象必须是整数
@parampreScale原是是几进制数
@paramnextScale 要转换成几进制数
String.prototype.scaleShift=function(preScale,nextScale){
returnparseInt(this,preScale).toString(nextScale);
}
全角2半角document.write("ABC123,我们都是好朋友");
String.prototype.dbc2sbc=function(){
returnthis.replace(/[\uff01-\uff5e]/g,function(a){returnString.fromCharCode(a.charCodeAt(0)-65248);}).replace(/\u3000/g,"");
}
Array扩展函数:
varisNumeric=function(x){
//returnstrueifxisnumericandfalseifitisnot.
varRegExp=/^(-)?(\d*)(\.?)(\d*)$/;
returnString(x).match(RegExp);
}
varmyArray=[1,'two',3,'four',5,'six',7,'eight',9,'ten'];
varoddArray=myArray.filter(isNumeric);//outputs:1,3,5,7,9
varoddArray=myArray.some(isNumeric);//outputs:true
varoddArray=myArray.every(isNumeric);//outputs:false
varprintArray=function(x,idx){
document.writeln('['+idx+']='+x);
}
myArray.forEach(printArray);//outputs:[0]=1[1]=two[2]=3[3]=four[4]=5
myArray.remove(9);
document.writeln(myArray);
if(!Array.prototype.every)
{
Array.prototype.every=function(fun/*,thisp*/)
{
varlen=this.length;
if(typeoffun!="function")
thrownewTypeError();
varthisp=arguments[1];
for(vari=0;i<len;i++)
{
if(iinthis&&
!fun.call(thisp,this[i],i,this))
returnfalse;
}
returntrue;
};
}
if(!Array.prototype.filter)
{
Array.prototype.filter=function(fun/*,thisp*/)
{
varlen=this.length;
if(typeoffun!="function")
thrownewTypeError();
varres=newArray();
varthisp=arguments[1];
for(vari=0;i<len;i++)
{
if(iinthis)
{
varval=this[i];//incasefunmutatesthis
if(fun.call(thisp,val,i,this))
res.push(val);
}
}
returnres;
};
}
if(!Array.prototype.forEach)
{
Array.prototype.forEach=function(fun/*,thisp*/)
{
varlen=this.length;
if(typeoffun!="function")
thrownewTypeError();
varthisp=arguments[1];
for(vari=0;i<len;i++)
{
if(iinthis)
fun.call(thisp,this[i],i,this);
}
};
}
if(!Array.prototype.map)
{
Array.prototype.map=function(fun/*,thisp*/)
{
varlen=this.length;
if(typeoffun!="function")
thrownewTypeError();
varres=newArray(len);
varthisp=arguments[1];
for(vari=0;i<len;i++)
{
if(iinthis)
res[i]=fun.call(thisp,this[i],i,this);
}
returnres;
};
}
if(!Array.prototype.some)
{
Array.prototype.some=function(fun/*,thisp*/)
{
varlen=this.length;
if(typeoffun!="function")
thrownewTypeError();
varthisp=arguments[1];
for(vari=0;i<len;i++)
{
if(iinthis&&
fun.call(thisp,this[i],i,this))
returntrue;
}
returnfalse;
};
}
Array.prototype.sortNum=function(){
returnthis.sort(function(a,b){returna-b;});
}
<!--
vartmp=[5,9,12,18,56,1,10,42,'blue',30,7,97,53,33,30,35,27,30,'35','Ball','bubble'];
varthirty=tmp.find(30);//Returns9,14,17
varthirtyfive=tmp.find('35');//Returns18
varthirtyfive=tmp.find(35);//Returns15
varhaveBlue=tmp.find('blue');//Returns8
varnotFound=tmp.find('notthere!');//Returnsfalse
varregexp1=tmp.find(/^b/);//returns8,20(firstletterstartswithb)
varregexp1=tmp.find(/^b/i);//returns8,19,20(sameasabovebutignorecase)
-->
Array.prototype.find=function(searchStr){
varreturnArray=false;
for(i=0;i<this.length;i++){
if(typeof(searchStr)=='function'){
if(searchStr.test(this[i])){
if(!returnArray){returnArray=[]}
returnArray.push(i);
}
}else{
if(this[i]===searchStr){
if(!returnArray){returnArray=[]}
returnArray.push(i);
}
}
}
returnreturnArray;
}
随机改变数组的排序
Array.prototype.shuffle=function(){
for(varrnd,tmp,i=this.length;i;rnd=parseInt(Math.random()*i),tmp=this[--i],this[i]=this[rnd],this[rnd]=tmp);
returnthis;
}
<!--varmyArray=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
varyourArray=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
document.writeln(myArray.compare(yourArray));//outputs:true;-->
Array.prototype.compare=function(testArr){
if(this.length!=testArr.length)returnfalse;
for(vari=0;i<testArr.length;i++){
if(this[i].compare){
if(!this[i].compare(testArr[i]))returnfalse;
}
if(this[i]!==testArr[i])returnfalse;
}
returntrue;
}
去掉数组中重复的值vara=newArray("5","7","7");a.unique();
Array.prototype.unique=function(){
vardata=this||[];
vara={};//声明一个对象,javascript的对象可以当哈希表用
for(vari=0;i<data.length;i++){
a[data[i]]=true;//设置标记,把数组的值当下标,这样就可以去掉重复的值
}
data.length=0;
for(variina){//遍历对象,把已标记的还原成数组
this[data.length]=i;
}
returndata;
}
Array.prototype.addAll=function($array)
{
if($array==null||$array.length==0)
return;
for(var$i=0;$i<$array.length;$i++)
this.push($array[$i]);
}
Array.prototype.contains=function($value)
{
for(var$i=0;$i<this.length;$i++)
{
var$element=this[$i];
if($element==$value)
returntrue;
}
returnfalse;
}
Array.prototype.indexOf=function($value)
{
for(var$i=0;$i<this.length;$i++)
{
if(this[$i]==$value)
return$i;
}
return-1;
}
if(!Array.prototype.lastIndexOf)
{
Array.prototype.lastIndexOf=function(elt/*,from*/)
{
varlen=this.length;
varfrom=Number(arguments[1]);
if(isNaN(from))
{
from=len-1;
}
else
{
from=(from<0)
?Math.ceil(from)
:Math.floor(from);
if(from<0)
from+=len;
elseif(from>=len)
from=len-1;
}
for(;from>-1;from--)
{
if(frominthis&&
this[from]===elt)
returnfrom;
}
return-1;
};
}
Array.prototype.insertAt=function($value,$index)
{
if($index<0)
this.unshift($value);
elseif($index>=this.length)
this.push($value);
else
this.splice($index,0,$value);
}
根据数组的下标来删除元素
Array.prototype.removeByIndex=function($n){
if($n<0){//如果n<0,则不进行任何操作。
returnthis;
}else{
returnthis.slice(0,$n).concat(this.slice($n+1,this.length));
}
}
依赖indexOf
Array.prototype.remove=function($value)
{
var$index=this.indexOf($value);
if($index!=-1)
this.splice($index,1);
}
Array.prototype.removeAll=function()
{
while(this.length>0)
this.pop();
}
Array.prototype.replace=function($oldValue,$newValue)
{
for(var$i=0;$i<this.length;$i++)
{
if(this[$i]==$oldValue)
{
this[$i]=$newValue;
return;
}
}
}
Array.prototype.swap=function($a,$b)
{
if($a==$b)
return;
var$tmp=this[$a];
this[$a]=this[$b];
this[$b]=$tmp;
}
Array.prototype.max=function(){
returnMath.max.apply({},this);
}
Array.prototype.min=function(){
returnMath.min.apply({},this);
}
Array.prototype.splice=function(start,delLen,item){
varlen=this.length;
start=start<0?0:start>len?len:start?start:0;
delLen=delLen<0?0:delLen>len?len:delLen?delLen:len;
vararr=[],res=[];
variarr=0,ires=0,i=0;
for(i=0;i<len;i++){
if(i<start||ires>=delLen)arr[iarr++]=this[i];
else{
res[ires++]=this[i];
if(item&&ires==delLen){
arr[iarr++]=item;
}
}
}
if(item&&ires<delLen)arr[iarr]=item;
for(vari=0;i<arr.length;i++){
this[i]=arr[i];
}
this.length=arr.length;
returnres;
}
Array.prototype.shift=function(){if(!this)return[];returnthis.splice(0,1)[0];}
分开添加,关键字shallowcopy,如果遇到数组,复制数组中的元素
Array.prototype.concat=function(){
vari=0;
while(i<arguments.length){
if(typeofarguments[i]==='object'&&typeofarguments[i].splice==='function'&&!arguments[i].propertyIsEnumerable('length')){
//NOTSHALLOWCOPYBELOW
//Array.prototype.concat.apply(this,arguments[i++]);
varj=0;
while(j<arguments[i].length)this.splice(this.length,0,arguments[i][j++]);
i++;
}else{
this[this.length]=arguments[i++];
}
}
returnthis;
}
Array.prototype.join=function(separator){
vari=0,str="";
while(i<this.length)str+=this[i++]+separator;
returnstr;
}
Array.prototype.pop=function(){returnthis.splice(this.length-1,1)[0];}
Array.prototype.push=function(){
Array.prototype.splice.apply(this,
[this.length,0].concat(Array.prototype.slice.apply(arguments)));//这里没有直接处理参数,而是复制了一下
returnthis.length;
}
Array.prototype.reverse=function(){
for(vari=0;i<this.length/2;i++){
vartemp=this[i];
this[i]=this[this.length-1-i];
this[this.length-1-i]=temp;
}
returnthis;
}
Array.prototype.slice=function(start,end){
varlen=this.length;
start=start<0?start+=len:start?start:0;
end=end<0?end+=len:end>len?len:end?end:len;
vari=start;
varres=[];
while(i<end){
res.push(this[i++]);
}
returnres;
}
//arr.unshift(ele1,ele2,ele3....)
Array.prototype.unshift=function(){
Array.prototype.splice.apply(this,[0,0].concat(Array.prototype.slice.apply(this,arguments)));
}