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.