stringHandle.js
1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
* @Author: Targaryen
* @Date: 2017-05-22 16:48:15
* @Last Modified by: Targaryen
* @Last Modified time: 2017-05-22 16:53:18
*/
let stringHandle = {
/**
* 汉字相当于两个字符的字符串长度计算
* @param {*} str
*/
chinese2(str) {
let total = 0,
charCode,
i,
len;
for (i = 0, len = str.length; i < len; i++) {
charCode = str.charCodeAt(i);
if (charCode <= 0x007f) {
total += 1;
} else {
total += 2;
}
}
return total;
},
/**
* 中文相当于两个字符情况下的字符串截取
* @param {*} str
* @param {*} n
*/
sub_chinese2(str, n) {
let r = /[\u4E00-\u9FA5]/g;
if (str.replace(r, 'mm').length <= n) {
return str;
}
let m = Math.floor(n / 2);
for (let i = m; i < str.length; i++) {
if (str.substr(0, i).replace(r, 'mm').length >= n) {
return str.substr(0, i);
}
}
return str;
}
};
module.exports = stringHandle;