forked from foru17/chinese-s2t
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (66 loc) · 1.35 KB
/
index.js
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* Author:luolei
* Module dependencies.
* 简繁体转换
*/
'use strict';
var Zh_Data = require('./lang/zh.js');
/**
* 简体字
*/
var S = Zh_Data.S;
/**
* 繁体字
*/
var T = Zh_Data.T;
/**
* 转换文本
* @param {String} str - 待转换的文本
* @param {Boolean} toT - 是否转换成繁体
* @returns {String} - 转换结果
*/
function tranStr(str, toT) {
var i;
var letter;
var code;
var isChinese;
var index;
var src, des;
var result = '';
if (toT) {
src = S;
des = T;
} else {
src = T;
des = S;
}
if (typeof str !== "string") {
return str;
}
for (i = 0; i < str.length; i++) {
letter = str.charAt(i);
code = str.charCodeAt(i);
// 根据字符的Unicode判断是否为汉字,以提高性能
isChinese = (code > 0x3400 && code < 0x9FC3) || (code > 0xF900 && code < 0xFA6A);
if (!isChinese) {
result += letter;
continue;
}
index = src.indexOf(letter);
if (index !== -1) {
result += des.charAt(index);
} else {
result += letter;
}
}
return result;
}
var Chinese = {
s2t:function(string){
return tranStr(string,true)
},
t2s:function(string){
return tranStr(string,false)
}
}
module.exports = Chinese;