Summary of JavaScript common string and array extension functions

  • 2021-02-17 06:16:34
  • OfStack

The extension function of the String object:


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,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); 
} 
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);   
} 

Variable substitution


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]; 
  }); 
} 

Appends a string to the end of a string


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

Deletes the character at the specified index position. Invalid index will not delete any characters


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); 
  } 
} 

Deletes the string between the specified indexes.$sIndex and $eIndex characters are not deleted! Rely on 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); 
  } 
} 

Check if the string ends with a string (str)


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

Checks if the string starts with a string


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

Compare two strings for equality, case insensitive!


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

Inserts the specified string after the specified position! Invalid indexes are appended directly to the end of the string


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); 
} 

Sets a character at the specified position to another specified character or string. Invalid index will be returned without any processing!


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;  
} 

Extending base classes:
Replace characters. This is useful when filling in substitutions, such as *** day *** hour with < input / > day < input / > hours


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]; 
  }); 
} 

0

Arrange the string in reverse order


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

Calculate the length, two lengths for each Chinese character and one length for each English character


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; 
} 

Fill the left side of the string with 1 of the specified characters


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]; 
  }); 
} 

3

Piles 1 character to the right of the string


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]; 
  }); 
} 

4

Converts the first letter of a string to uppercase


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]; 
  }); 
} 

5

Converts a string formatted as 2008-04-02 10:08:44 to a date (the value of the String object must be 2008-04-02 10:08:44)


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]; 
  }); 
} 

6

Converts a decimal number originally represented by a string to a decimal floating-point number: precision for precision


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

Converts a decimal number originally represented as a string to a decimal integer


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

Returns as a string the sum of two decimal digits originally represented as a string: addend is the addend


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]; 
  }); 
} 

9

10 to other base code as follows nextScale for base such as 2,8,16


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


Each base is converted to another:
The this object must be an integer
param preScale was originally a decimal number
@param nextScale to be converted to a decimal number


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

document.write("ABC123, we are all good friends ");
String.prototype.dbc2sbc = function (){
return this.replace(/[\uff01-\uff5e]/g,function(a){return String.fromCharCode(a.charCodeAt(0)-65248);}).replace(/\u3000/g," ");
}


Array extension function:


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; 
} 

Randomly changes the sorting of arrays


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 = {}; // The statement 1 An object, javascript Objects of the  
  for (var i = 0; i < data.length; i++) { 
    a[data[i]] = true; // Set the flag to the array value as the index, so that you can get rid of duplicate values  
  } 
  data.length = 0;  
   
  for (var i in a) { // Iterate through the object, restoring the marked ones to an array  
    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); 
} 


Deletes elements based on the index of an array


Array.prototype.removeByIndex=function($n) {   
  if($n<0){ // if n<0 , nothing is done.   
    return this;  
  }else{  
    return this.slice(0,$n).concat(this.slice($n+1,this.length));  
  }  
} 

Rely on 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];} 


Add it separately, shallow, copy, and if you encounter an array, copy the elements of the array


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))); // Instead of processing the parameters directly, they are copied 1 Under the  
  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))); 
} 


Related articles: