Home  >  Article  >  Web Front-end  >  Example of using regular expressions to calculate the length of Chinese characters in javascript_javascript skills

Example of using regular expressions to calculate the length of Chinese characters in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:50:45987browse

Since JavaScript is unicode encoded, all characters are one for it, but not for the background program. Usually, one Chinese character in the background program occupies two bytes, which leads to the front-end and back-end verification length. Inconsistency, this problem can be solved through regularization.

Copy code The code is as follows:

function getRealLen( str ) {
return str. replace(/[^x00-xff]/g, '__').length; //This matches all double-byte characters
}

Another little tip is included :

Sometimes, for the sake of beauty and not affecting the layout and interface, some copywriting will be truncated. However, the width of Chinese and English are different. If the Chinese is truncated according to English standards, or the English is truncated according to Chinese standards, Obviously it will be long and short, especially things like nicknames that are easy to have both Chinese and English. We can also use the above idea

Copy code The code is as follows:

function beautySub( str, len) {
var reg = /[u4e00-u9fa5]/g, //Professional matching Chinese
slice = str.substring(0,len),
              realen = len - ( ~~( slice.match(reg) && slice.match(reg).length) ); realen : 1);
}
Here we think that one Chinese character is the width of two English characters. If you are a perfectionist, you should think that the widths of j, w, and m are different. The widths of w, m and some uppercase letters are consistent with Chinese. There is considerable room for improvement in the regularity of this function, and the starting position of the truncation can also be specified.
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