Summary of common JavaScript strings and array extended functions _ basic knowledge

Source: Internet
Author: User
This article mainly introduces some common JavaScript strings and Array Extension functions, and sorts out some simple and frequently-used String and Array functions. For more information, see Extended functions of String objects:

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.html Entities = function () {return this. 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
 
  

Variable replacement

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

Append a string to the end of the string

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

Delete the character at the specified index location. If the index is invalid, no characters will be deleted.

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

Deleting the strings. $ sIndex and $ eIndex between specified indexes is not deleted! Dependency 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 whether the string ends with a string (str)

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

Check whether the string starts with a certain string

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

Compare the two strings to see if they are equal, 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;   } } 

Insert the specified string to the end of the specified position! If the index is invalid, it will be appended 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); } 

Set the character at the specified position to another character or string. If the index is invalid, the system will return the result 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;  } 

Extended basic class:
Replace the character, which is useful when you replace it with. For example, replace itDaysHours

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

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

Calculates the length. Each Chinese Character occupies two lengths, and each English character occupies one length.

String.prototype.ucLength = function(){   var len = 0;   for(var i=0;i
   
    255)len+=2;     else len++;   }   return len; } 
   

Fill in some specific characters on the left of the string

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

Fill in some specific characters on the right of the string

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

Converts the first letter of a string to uppercase.

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

Convert a String in the format of 10:08:44 to a date (the value of the String object must be: 10:08:44)

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

Convert the decimal number represented by a string into a decimal floating point number: precision

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

Convert the decimal number represented by a string to a decimal integer.

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

Add two decimal numbers represented in the original string and return the result as a string: addend is the addition number.

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

The code for converting decimal to other hexadecimal formats is as follows: nextScale is in hexadecimal format, for example, 16.

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


Convert each other in hexadecimal notation:
This object must be an integer
@ Param preScale is a number in hexadecimal notation.
@ Param nextScale: Convert the data to a number in hexadecimal notation.

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

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


Array extended functions:

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 ;});}
   Array. prototype. find = function (searchStr) {var returnArray = false; for (I = 0; I
   
    

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

Remove the repeated values var a = new Array ("5", "7", "7"); a. unique ();

Array. prototype. unique = function () {var data = this | []; var a = {}; // declare an object, javascript objects can use for (var I = 0; I <data. length; I ++) {a [data [I] = true; // set the flag to use the value of the array as the subscript, so that duplicate values can be removed} data. length = 0; for (var I in a) {// traverses the object and restores the marked object to the 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
     
      
= 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 an element based on the subscript of the array.

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

Dependent 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
     
      
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
      
       
= DelLen) arr [iarr ++] = this [I]; else {res [ires ++] = this [I]; if (item & ires = delLen) {arr [iarr ++] = item ;}} if (item & ires
       
        


Added separately. The key word is shallow copy. If an array is encountered, copy the elements in the array.

Array.prototype.concat = function(){   var i=0;   while(ilen?len:end?end:len;          var i=start;   var res = [];   while(i
         
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.