stringHandle.js
1.16 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
/*
* @Author: Targaryen
* @Date: 2017-05-22 16:48:15
* @Last Modified by: Targaryen
* @Last Modified time: 2017-05-22 16:53:18
*/
var stringHandle = {
/**
* 汉字相当于两个字符的字符串长度计算
* @param {*} str
*/
chinese2: function(str) {
var 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: function(str, n) {
var r = /[\u4E00-\u9FA5]/g;
var m = Math.floor(n / 2);
var i;
if (str.replace(r, 'mm').length <= n) {
return str;
}
for (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;