How to get the length of mixed strings in Chinese and English in JavaScript

Source: Internet
Author: User
Tags array length character set mixed regular expression

  This article describes how to get the length of the mixed string in Chinese and English under JavaScript, here is a good tutorial, interested friends can refer to the following

A colleague posted a post on the company's OA, describing how to get the length of the mixed string in the JavaScript language.     is using regular expressions.       Code as follows: var str = "Tank is Tank";  var len = str.match (/[^-~]/g) = = null? Str.length:str.length + str.match (/[^-~]/g). length;    I checked the book.:    Latin Common character set by Space "" (0x20) to "~" (0 x7e), the Chinese character will fall outside the character set, while the regular expression [^-~] represents a character set except for spaces to "~".     Code as follows: the String.match (regex) returns the substring of a string in strings that matches the regex of the regular expression in the form of an array, so,  Str.match (/[^-~]/g) Returns a Chinese character as an array. For example   var str = "Brother DD"; //Show "big, elder brother", the array returns two characters, the array length is 2  alert (Str.match (/[^-~]/g));    So, var len = s Tr.match (/[^-~]/g) = null? Str.length:str.length + str.match (/[^-~]/g). length; You can get the correct lengths of Str.     in JavaScript, the length of a Chinese character is also calculated to be 1, often in the submission to the database caused by the error of the length exceeded, now use this method, can be detected before submitting.     NOTE: Some symbols of the above code problems, after the amendment, to the following function.   Code as follows: function Get_strlength (str)   {  var len = 0;    if (Str.match (/[^-~]/g) = null)   {  len = str.length; }  else  {  len = str.length + str.Match (/[^-~]/g) .length; }    return len; }   
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.