Five methods for determining the string length in JS

Source: Internet
Author: User

This article mainly introduces five methods for determining the string length in JS and distinguishes Chinese and English. For more information, see

Objective: To calculate the String length (1 character in English and 2 Characters in Chinese) Method 1: the code is as follows: String. prototype. gblen = function () {var len = 0; for (var I = 0; I <this. length; I ++) {if (this. charCodeAt (I)> 127 | this. charCodeAt (I) = 94) {len + = 2;} else {len ++;} return len;} Method 2: the code is as follows: function strlen (str) {var len = 0; for (var I = 0; I <str. length; I ++) {var c = str. charCodeAt (I); // Add 1 if (c> = 0x0001 & c <= 0x007e) to a single byte | (0xff60 <= c & c <= 0xff9f) {Len ++;} else {len + = 2 ;}} return len ;}method 3: Code: var jmz ={}; jmz. getLength = function (str) {// <summary> obtain the actual length of the string, which is 2 in Chinese, english 1 </summary> // <param name = "str"> string to be obtained </param> var realLength = 0, len = str. length, charCode =-1; for (var I = 0; I <len; I ++) {charCode = str. charCodeAt (I); if (charCode> = 0 & charCode <= 128) realLength + = 1; else realLength + = 2;} return realLength ;}; Method 4: Code Var l = str. length; var blen = 0; for (I = 0; I <l; I ++) {if (str. charCodeAt (I) & 0xff00 )! = 0) {blen ++;} Method 5: Replace the dual-byte with two single-byte values and obtain the Length Code as follows: getBLen = function (str) {if (str = null) return 0; if (typeof str! = "String") {str + = "";} return str. replace (/[^ \ x00-\ xff]/g, "01"). length ;}

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.