js accurate calculation of the string length in bytes

String.prototype.byteLength = function () {// Get the number of bytes of the string 
    var b = 0, l = this.length ; // initializes the number of bytes and incrementing the variable number of characters of the string parameter acquired 
    if ( l) {// If the string is present, the execution plan 
        for (var i = 0; i <l; i ++) {// iterate string, each character enumeration 
            if (this.charCodeAt (i)> 255 ) {// character code is greater than 255, indicating that the double-byte character 
                b + = 2; // the accumulated 2 
            } the else { 
                B ++; // otherwise, incrementing once 
            } 
        } 
        return B; // returns the number of bytes 
    the else {} 
        return 0; // If the argument is null, then return 0 
    } 
}

  

use:

var s = "String Type Length"; // define string literals 
console.log (s.byteLength ()); // 14

  

Guess you like

Origin www.cnblogs.com/zaijin-yang/p/12176945.html