JavaScript常用字符串与数组扩展函数小结


Posted in Javascript onApril 24, 2016

String对象的扩展函数:

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,""); 
} 
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 () { 
  return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); 
} 
String.prototype.stripTags = function () { 
  return this.replace(/<([^>]+)>/g,''); 
} 
String.prototype.toArray = function() { 
  return this.split(''); 
} 
String.prototype.toIntArray = function() { 
  var returnArray = []; 
  for (var i=0; i<this.length; i++) { 
   returnArray.push(this.charCodeAt(i)); 
  } 
  return returnArray; 
} 
String.prototype.replaceAll = function($old, $snew){   
  return this.replace(new RegExp($old,"gm"),$snew);   
}

变量替换

var a = "I Love {0}, and You Love {1},Where are {0}!";a.format("You","Me"); 
String.prototype.format = function(){ 
  var args = arguments; 
  return this.replace(/\{(\d+)\}/g,function(m,i,o,n){ 
    return args[i]; 
  }); 
}

在字符串末尾追加字符串 

String.prototype.append = function($str){ 
  return this.concat($str); 
}

删除指定索引位置的字符,索引无效将不删除任何字符 

String.prototype.deleteCharAt = function($sIndex){ 
  if($sIndex<0 || $sIndex>=this.length){ 
    return this.valueOf(); 
  }else if($sIndex==0){ 
    return this.substring(1,this.length); 
  }else if($sIndex==this.length-1){ 
    return this.substring(0,this.length-1); 
  }else{ 
    return this.substring(0,$sIndex)+this.substring($sIndex+1); 
  } 
}

删除指定索引间的字符串.$sIndex和$eIndex所在的字符不被删除!依赖deleteCharAt  

String.prototype.deleteString = function($sIndex, $eIndex){ 
  if($sIndex==$eIndex){ 
    return this.deleteCharAt($sIndex); 
  }else{ 
    if($sIndex>$eIndex){ 
      var tIndex=$eIndex; 
      $eIndex=$sIndex; 
      $sIndex=tIndex; 
    } 
    if($sIndex<0)$sIndex=0; 
    if($eIndex>this.length-1)$eIndex=this.length-1; 
    return this.substring(0,$sIndex+1)+this.substring($eIndex,this.length); 
  } 
}

检查字符串是否以某个字符串(str)结尾 

String.prototype.endsWith = function($str){ 
  return this.substr(this.length - $str.length) == $str; 
}

检查该字符串是否以某个字符串开始 

String.prototype.startsWith = function(str){ 
  return this.substr(0, str.length) == str; 
}

比较两个字符串是否相等,不区分大小写! 

String.prototype.equalsIgnoreCase = function($str){ 
  if(this.length!=$str.length){ 
    return false; 
  }else{ 
    var tmp1=this.toLowerCase(); 
    var tmp2=$str.toLowerCase(); 
    return tmp1==tmp2; 
  } 
}

将指定的字符串插入到指定的位置后面!索引无效将直接追加到字符串的末尾 

String.prototype.insert = function($ofset, $str){ 
  if($ofset<0 || $ofset>=this.length-1){ 
    return this.concat($str); 
  } 
  return this.substring(0,$ofset)+$str+this.substring($ofset+1); 
}

将指定的位置的字符设置为另外指定的字符或字符串.索引无效将直接返回不做任何处理!  

String.prototype.setCharAt = function($ofset, $str){ 
  if($ofset<0 || $ofset>=this.length-1){ 
    return this.valueOf(); 
  } 
  return this.substring(0,$ofset)+$str+this.substring($ofset+1); 
} 
String.prototype.replaceLen = function(start, len, replaced) {  
  if(!len)  
    return this;  
 
  if(start >= this.length)  
    return this;  
 
  var returnSeg = '';  
  var returnSeg2 = '';  
  var i = 0;  
  for (; i < this.length; i++){  
    var c = this.charAt(i);  
    if(i < start)  
      returnSeg += c;  
 
    if(i >= start + len)  
      returnSeg2 += c;  
  }  
 
  return returnSeg + replaced + returnSeg2;  
}

扩展基础类: 
替换字符,这个在替换填入比较有用,比如***天***小时 替换为 <input />天<input />小时  
 

String.prototype.replaceChar = function(target, replaced, start) {  
  if(!target)  
    return this;  
  if(!start)  
    start = 0;  
 
  var returnVal = this.substring(0, start);  
  var index = 0;  
  for (var i = start; i < this.length; i++) {  
    var c = this.charAt(i);  
    target = typeof target == 'function' ? target.call(this, index) : target;  
    if (c == target) {  
      returnVal += typeof replaced == 'function' ? replaced.call(this, index) : replaced;  
      while (i < this.length - 1 && this.charAt(i + 1) == c) {  
        i++;  
      }  
      index++;  
    }else{  
      returnVal += c;  
    }  
  }  
 
  return returnVal;  
}

将该字符串反序排列 

String.prototype.reverse = function(){ 
  var str=""; 
  for(var i=this.length-1;i>=0;i--){ 
    str=str.concat(this.charAt(i)); 
  } 
  return str; 
}

计算长度,每个汉字占两个长度,英文字符每个占一个长度 

String.prototype.ucLength = function(){ 
  var len = 0; 
  for(var i=0;i<this.length;i++){ 
    if(this.charCodeAt(i)>255)len+=2; 
    else len++; 
  } 
  return len; 
}

在字符串的左边填充一些特定的字符 

String.prototype.lpad = function(len, s) { 
  var a = new Array(this); 
  var n = (len - this.length); 
  for ( var i = 0; i < n; i++) { 
    a.unshift(s); 
  } 
  return a.join(""); 
}

在字符串的右边填充一些特定的字符 

String.prototype.rpad = function(len, s) { 
  var a = new Array(this); 
  var n = (len - this.length); 
  for ( var i = 0; i < n; i++) { 
    a.push(s); 
  } 
  return a.join(""); 
}

把字符串的首字母转化为大写 

String.prototype.ucwords = function() { 
  return this.substring(0,1).toUpperCase().concat(this.substring(1)); 
} 
String.prototype.contains = function($str) { 
  return this.indexOf($str) > -1 ? true : false; 
}

将格式为2008-04-02 10:08:44的字符串转成日期(String对象的值必须为: 2008-04-02 10:08:44) 

String.prototype.toDate = function(){ 
  var str = this.replace(/-/g,"/"); 
  return (new Date(str)); 
}

将原来用字符串表示的十进数转成十进制浮点数: precision为精度 

String.prototype.toFloat = function(precision){ 
  precision = precision || 2; 
  return parseFloat(this,10).toFixed(precision); 
}

将原来用字符串表示的十进数转成十进制整数 

String.prototype.toInt = function(){ 
  return parseInt(this,10).toString(); 
}

将两个原来用字符串表示的十进数相加后当作字串返回 : addend为加数 

String.prototype.add = function(addend){ 
  var sum = parseFloat(this,10) + parseFloat(addend,10); 
  return sum+""; 
}

十进制转其他进制代码如下nextScale为进制 如2,8,16 

String.prototype.shiftScale = function(nextScale){ 
  return parseFloat(this).toString(nextScale); 
}

各进制互相转换 :
this对象必须是整数
@param preScale 原是是几进制数
@param nextScale  要转换成几进制数 
 

String.prototype.scaleShift = function(preScale,nextScale){ 
  return parseInt(this,preScale).toString(nextScale); 
}

全角2半角 document.write("ABC 123,我们都是好朋友"); 
String.prototype.dbc2sbc = function (){ 
    return this.replace(/[\uff01-\uff5e]/g,function(a){return String.fromCharCode(a.charCodeAt(0)-65248);}).replace(/\u3000/g," "); 

Array扩展函数:

var isNumeric = function(x) { 
  // returns true if x is numeric and false if it is not. 
  var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;  
  return String(x).match(RegExp); 
} 
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,'ten']; 
var oddArray=myArray.filter(isNumeric); // outputs: 1,3,5,7,9 
var oddArray=myArray.some(isNumeric); // outputs: true 
var oddArray=myArray.every(isNumeric); // outputs: false 
var printArray =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*/) 
 { 
  var len = this.length; 
  if (typeof fun != "function") 
   throw new TypeError(); 
 
  var thisp = arguments[1]; 
  for (var i = 0; i < len; i++) 
  { 
   if (i in this && 
     !fun.call(thisp, this[i], i, this)) 
    return false; 
  } 
 
  return true; 
 }; 
} 
if (!Array.prototype.filter) 
{ 
 Array.prototype.filter = function(fun /*, thisp*/) 
 { 
  var len = this.length; 
  if (typeof fun != "function") 
   throw new TypeError(); 
 
  var res = new Array(); 
  var thisp = arguments[1]; 
  for (var i = 0; i < len; i++) 
  { 
   if (i in this) 
   { 
    var val = this[i]; // in case fun mutates this 
    if (fun.call(thisp, val, i, this)) 
     res.push(val); 
   } 
  } 
 
  return res; 
 }; 
} 
if (!Array.prototype.forEach) 
{ 
 Array.prototype.forEach = function(fun /*, thisp*/) 
 { 
  var len = this.length; 
  if (typeof fun != "function") 
   throw new TypeError(); 
 
  var thisp = arguments[1]; 
  for (var i = 0; i < len; i++) 
  { 
   if (i in this) 
    fun.call(thisp, this[i], i, this); 
  } 
 }; 
} 
if (!Array.prototype.map) 
{ 
 Array.prototype.map = function(fun /*, thisp*/) 
 { 
  var len = this.length; 
  if (typeof fun != "function") 
   throw new TypeError(); 
 
  var res = new Array(len); 
  var thisp = arguments[1]; 
  for (var i = 0; i < len; i++) 
  { 
   if (i in this) 
    res[i] = fun.call(thisp, this[i], i, this); 
  } 
 
  return res; 
 }; 
} 
if (!Array.prototype.some) 
{ 
 Array.prototype.some = function(fun /*, thisp*/) 
 { 
  var len = this.length; 
  if (typeof fun != "function") 
   throw new TypeError(); 
 
  var thisp = arguments[1]; 
  for (var i = 0; i < len; i++) 
  { 
   if (i in this && 
     fun.call(thisp, this[i], i, this)) 
    return true; 
  } 
 
  return false; 
 }; 
} 
Array.prototype.sortNum = function() { 
  return this.sort( function (a,b) { return a-b; } ); 
} 
<!-- 
var tmp = [5,9,12,18,56,1,10,42,'blue',30, 7,97,53,33,30,35,27,30,'35','Ball', 'bubble']; 
var thirty=tmp.find(30);       // Returns 9, 14, 17 
var thirtyfive=tmp.find('35');    // Returns 18 
var thirtyfive=tmp.find(35);     // Returns 15 
var haveBlue=tmp.find('blue');    // Returns 8 
var notFound=tmp.find('not there!'); // Returns false 
var regexp1=tmp.find(/^b/);     // returns 8,20  (first letter starts with b) 
var regexp1=tmp.find(/^b/i);     // returns 8,19,20 (same as above but ignore case) 
--> 
Array.prototype.find = function(searchStr) { 
 var returnArray = 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); 
   } 
  } 
 } 
 return returnArray; 
}

随机改变数组的排序 

Array.prototype.shuffle = function (){   
  for(var rnd, tmp, i=this.length; i; rnd=parseInt(Math.random()*i), tmp=this[--i], this[i]=this[rnd], this[rnd]=tmp);  
  return this; 
}   
<!--var myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; 
var yourArray = [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) return false; 
  for (var i = 0; i < testArr.length; i++) { 
    if (this[i].compare) {  
      if (!this[i].compare(testArr[i])) return false; 
    } 
    if (this[i] !== testArr[i]) return false; 
  } 
  return true; 
}

去掉数组中重复的值var a = new Array("5","7","7"); a.unique(); 

Array.prototype.unique = function() { 
  var data = this || []; 
  var a = {}; //声明一个对象,javascript的对象可以当哈希表用 
  for (var i = 0; i < data.length; i++) { 
    a[data[i]] = true; //设置标记,把数组的值当下标,这样就可以去掉重复的值 
  } 
  data.length = 0;  
   
  for (var i in a) { //遍历对象,把已标记的还原成数组 
    this[data.length] = i;  
  }  
  return data; 
} 
 
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) 
      return true; 
  } 
 
  return false; 
} 
 
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*/) 
 { 
  var len = this.length; 
 
  var from = Number(arguments[1]); 
  if (isNaN(from)) 
  { 
   from = len - 1; 
  } 
  else 
  { 
   from = (from < 0) 
      ? Math.ceil(from) 
      : Math.floor(from); 
   if (from < 0) 
    from += len; 
   else if (from >= len) 
    from = len - 1; 
  } 
 
  for (; from > -1; from--) 
  { 
   if (from in this && 
     this[from] === elt) 
    return from; 
  } 
  return -1; 
 }; 
} 
Array.prototype.insertAt = function($value, $index) 
{ 
  if($index < 0) 
    this.unshift($value); 
  else if($index >= this.length) 
    this.push($value); 
  else 
    this.splice($index, 0, $value); 
}

根据数组的下标来删除元素  
 

Array.prototype.removeByIndex=function($n) {   
  if($n<0){ //如果n<0,则不进行任何操作。  
  return this;  
  }else{  
    return this.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() {  
  return Math.max.apply({}, this);  
}  
Array.prototype.min = function() {  
  return Math.min.apply({}, this);  
}  
Array.prototype.splice = function(start, delLen, item){ 
  var len =this.length; 
  start = start<0?0:start>len?len:start?start:0; 
  delLen=delLen<0?0:delLen>len?len:delLen?delLen:len;   
   
  var arr =[],res=[]; 
  var iarr=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(var i=0;i<arr.length;i++){ 
    this[i]=arr[i]; 
  } 
  this.length=arr.length; 
  return res; 
} 
Array.prototype.shift = function(){ if(!this) return[];return this.splice(0,1)[0];}

 
分开添加,关键字shallow copy,如果遇到数组,复制数组中的元素 

Array.prototype.concat = function(){ 
  var i=0; 
  while(i<arguments.length){ 
    if(typeof arguments[i] === 'object'&&typeof arguments[i].splice ==='function' &&!arguments[i].propertyIsEnumerable('length')){ 
    // NOT SHALLOW COPY BELOW 
    // Array.prototype.concat.apply(this,arguments[i++]); 
      var j=0; 
      while(j<arguments[i].length) this.splice(this.length,0,arguments[i][j++]); 
      i++; 
    } else{ 
      this[this.length]=arguments[i++]; 
    } 
  } 
  return this; 
} 
 
Array.prototype.join = function(separator){ 
  var i=0,str=""; 
  while(i<this.length) str+=this[i++]+separator; 
  return str; 
} 
 
Array.prototype.pop = function() { return this.splice(this.length-1,1)[0];} 
 
Array.prototype.push = function(){  
  Array.prototype.splice.apply(this, 
    [this.length,0].concat(Array.prototype.slice.apply(arguments))); //这里没有直接处理参数,而是复制了一下 
  return this.length; 
} 
Array.prototype.reverse = function(){ 
  for(var i=0;i<this.length/2;i++){ 
    var temp = this[i]; 
    this[i]= this[this.length-1-i]; 
    this[this.length-1-i] = temp; 
  } 
  return this; 
} 
Array.prototype.slice = function(start, end){ 
  var len =this.length; 
  start=start<0?start+=len:start?start:0; 
  end =end<0?end+=len:end>len?len:end?end:len; 
       
  var i=start; 
  var res = []; 
  while(i<end){ 
    res.push(this[i++]); 
  } 
  return res;  
} 
//arr.unshift(ele1,ele2,ele3....) 
Array.prototype.unshift =function(){ 
  Array.prototype.splice.apply(this,[0,0].concat(Array.prototype.slice.apply(this,arguments))); 
}
Javascript 相关文章推荐
JavaScript中的prototype使用说明
Apr 13 Javascript
JS刷新框架外页面七种实现代码
Feb 18 Javascript
解析javascript中鼠标滚轮事件
May 26 Javascript
谈谈基于iframe、FormData、FileReader三种无刷新上传文件的方法
Dec 03 Javascript
jQuery实现form表单元素序列化为json对象的方法
Dec 09 Javascript
12个非常实用的JavaScript小技巧【推荐】
May 18 Javascript
微信小程序 swiper组件详解及实例代码
Oct 25 Javascript
原生JS查找元素的方法(推荐)
Nov 22 Javascript
用vue2.0实现点击选中active其他选项互斥的效果
Apr 12 Javascript
浅谈webpack 构建性能优化策略小结
Jun 13 Javascript
详解Vue webapp项目通过HBulider打包原生APP
Jun 29 Javascript
实现AJAX异步调用和局部刷新的基本步骤
Mar 17 Javascript
javascript断点调试心得分享
Apr 23 #Javascript
基于 Node.js 实现前后端分离
Apr 23 #Javascript
javascript学习指南之回调问题
Apr 23 #Javascript
探寻JavaScript中this指针指向
Apr 23 #Javascript
javascript中this指向详解
Apr 23 #Javascript
JavaScript实现Base64编码转换
Apr 23 #Javascript
jQuery UI库中dialog对话框功能使用全解析
Apr 23 #Javascript
You might like
模拟OICQ的实现思路和核心程序(一)
2006/10/09 PHP
一个PHP分页类的代码
2011/05/18 PHP
php数组函数array_walk用法示例
2016/05/26 PHP
PHP扩展mcrypt实现的AES加密功能示例
2019/01/29 PHP
jquery 批量上传图片实现代码
2010/01/28 Javascript
js 分页全选或反选标识实现代码
2011/08/09 Javascript
jquery中focus()函数实现当对象获得焦点后自动把光标移到内容最后
2013/09/29 Javascript
jquery实现鼠标拖动图片效果示例代码
2014/01/09 Javascript
JS倒计时代码汇总
2014/11/25 Javascript
js控制文本框只输入数字和小数点的方法
2015/03/10 Javascript
Ionic3 UI组件之Gallery Modal详解
2017/06/07 Javascript
XMLHttpRequest对象_Ajax异步请求重点(推荐)
2017/09/28 Javascript
vue2.0 路由不显示router-view的解决方法
2018/03/06 Javascript
微信小程序支付前端源码
2018/08/29 Javascript
JS/jQuery实现获取时间的方法及常用类完整示例
2019/03/07 jQuery
javascript中如何判断类型汇总
2019/05/14 Javascript
小程序实现点击tab切换左右滑动
2020/11/16 Javascript
Python中optparse模块使用浅析
2015/01/01 Python
python中函数默认值使用注意点详解
2016/06/01 Python
Python闭包的两个注意事项(推荐)
2017/03/20 Python
Python中查看文件名和文件路径
2017/03/31 Python
python 实现登录网页的操作方法
2018/05/11 Python
Django中使用CORS实现跨域请求过程解析
2019/08/05 Python
django项目简单调取百度翻译接口的方法
2019/08/06 Python
Python restful框架接口开发实现
2020/04/13 Python
基于python SMTP实现自动发送邮件教程解析
2020/06/02 Python
python爬虫泛滥的解决方法详解
2020/11/25 Python
HomeAway英国:全球领先的度假租赁在线市场
2020/02/03 全球购物
高中生学习的自我评价
2013/12/14 职场文书
运动会开幕式主持词
2014/03/28 职场文书
岗位标兵事迹材料
2014/05/17 职场文书
汽车运用工程专业求职信
2014/06/18 职场文书
公司试用期员工自我评价
2014/09/17 职场文书
学校世界艾滋病日宣传活动总结
2015/05/05 职场文书
2016教师学习教育法心得体会
2016/01/19 职场文书
七年级上册生物的课件
2019/08/07 职场文书