Home  >  Article  >  Web Front-end  >  How to get the length of a mixed Chinese and English string in javascript_javascript skills

How to get the length of a mixed Chinese and English string in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:03:231467browse

A colleague posted a post on the company's OA, introducing how to get the length of a mixed Chinese and English string in JavaScript.

uses regular expressions.

Copy code The code is as follows:

var str = "tank is the transliteration of tank";
var len = str.match(/[^ -~]/g) == null ? str.length : str.length str.match(/[^ -~]/g).length ;

I checked the book and got it a little bit:

The commonly used Western character set consists of spaces " " (0x20) to "~" (0x7e). Chinese characters will fall outside this character set. The regular expression [^ -~] represents the character set except spaces to "~".
Copy code The code is as follows:

string.match(regex) will return characters in the form of an array The string matches the substring of the regular expression regex. Therefore,
str.match(/[^ -~]/g) will return Chinese characters one by one in the form of an array. For example
var str = "dd brother";
//Display "big brother", return two Chinese characters in the array, the array length is 2
alert(str.match(/[^ -~] /g));

In this way, var len = str.match(/[^ -~]/g) == null ? str.length : str.length str.match(/[^ -~]/g).length ;You can get the correct length of str.

In JavaScript, the length of a Chinese character is also calculated as 1, which often causes an error of exceeding the standard length when submitted to the database. Now with this method, you can check it before submitting.

Note: Some symbols in the above code have problems. After correction, they were changed to the following functions.
Copy code The code is 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;
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn