Examples of using regular computational Chinese length in JavaScript _javascript tips

Source: Internet
Author: User

Because JavaScript is Unicode encoded, all characters for it is one, but the background program is not, usually in the background of a Chinese language is two bytes, which leads to the front and back end checksum length inconsistency, this problem can be resolved through the regular.

Copy Code code as follows:

function Getreallen (str) {
Return str.replace (/[^\x00-\xff]/g, ' __ '). Length; This matches all the double-byte bits.
}

A small bonus tip:

Sometimes in order to be beautiful, without affecting the layout and interface, will take some copy of the word, but the width of Chinese and the width of English is not the same, if the English standard to intercept Chinese, or according to the Chinese standard section of English, obviously will be suddenly and short, especially nicknames such as easy to have both Chinese and English things, We can also use the above ideas

Copy Code code 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));
Return slice.substring (0, Realen realen:1);
}

Here we think that a Chinese character is the width of two English characters, if you are a perfectionist, you should think that the width of J and W,m is not the same, W and M and uppercase and lowercase letters and the width of the Chinese is consistent, this function is also a considerable improvement space, but also can specify the starting position of the truncated word.

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.