客户的需求是,输入半角字符或日语假名,筛选出来的结果显示包含该字符的半角形式和全角形式的所有结果,输入全角也是同样的结果。这里就需要将输入的字符全部转为半角和全角,再去匹配结果。
在网上搜了一圈之后,只找到了字符的全半角转换,日语的几乎没有,最后在GitHub到了自己想要的东西。
GitHub地址:https://github.com/shogo4405/KanaXS
Unicode中文和特殊字符的编码范围https://blog.csdn.net/lb521200200/article/details/53606864
字符的全半角转换如下:
全角转半角
function ToCDB(str) {
var tmp = "";
for (var i = 0; i < str.length; i++) {
if (str.charCodeAt(i) > 65248 && str.charCodeAt(i) < 65375) {
tmp += String.fromCharCode(str.charCodeAt(i) - 65248);
}
else {
tmp += String.fromCharCode(str.charCodeAt(i));
}
}
return tmp
}
半角转全角
function ToDBC(txtstring) {
var tmp = "";
for (var i = 0; i < txtstring.length; i++) {
if (txtstring.charCodeAt(i) == 32) {
tmp = tmp + String.fromCharCode(12288);
}
if (txtstring.charCodeAt(i) < 127) {
tmp = tmp + String.fromCharCode(txtstring.charCodeAt(i) + 65248);
}
}
if(isEmpty(tmp)){
return txtstring;
}
return tmp;
}
日语假名半角转全角
github上半角转全角的方法中,不包含小字符,如ぁ、ぃ、ぅ、ぇ、ぉ、っ、ゃ、ゅ、ょ
,所以我在js文件中进行了改良,加入了这些小字符的Unicode码对照。完整代码如下:
/**
* 半角のカタカナを全角のカタカナに変換します。
* @example
* "アイウエオ".toZenkanaCase(); // アイウエオ
* @return {String}
*/
String.prototype.toZenkanaCase = function(){
var i, f, c, a = [], m = String.prototype.toZenkanaCase.MAPPING;
for(i = 0, f = this.length;i < f; i++)
{
c = this.charCodeAt(i);
a.push(m[c] || c);
};
return String.fromCharCode.apply(null, a);
};
String.prototype.toZenkanaCase.MAPPING = {
0xFF67:0x30A1,
0xFF68:0x30A3,
0xFF69:0x30A5,
0xFF6A:0x30A7,
0xFF6B:0x30A9,
0xFF70:0x30FC,
0xFF71:0x30A2,
0xFF72:0x30A4,
0xFF73:0x30A6,
0xFF74:0x30A8,
0xFF75:0x30AA,
0xFF76:0x30AB,
0xFF77:0x30AD,
0xFF78:0x30AF,
0xFF79:0x30B1,
0xFF7A:0x30B3,
0xFF7B:0x30B5,
0xFF7C:0x30B7,
0xFF7D:0x30B9,
0xFF7E:0x30BB,
0xFF7F:0x30BD,
0xFF80:0x30BF,
0xFF81:0x30C1,
0xFF82:0x30C4,
0xFF83:0x30C6,
0xFF84:0x30C8,
0xFF85:0x30CA,
0xFF86:0x30CB,
0xFF87:0x30CC,
0xFF88:0x30CD,
0xFF89:0x30CE,
0xFF8A:0x30CF,
0xFF8B:0x30D2,
0xFF8C:0x30D5,
0xFF8D:0x30D8,
0xFF8E:0x30DB,
0xFF8F:0x30DE,
0xFF90:0x30DF,
0xFF91:0x30E0,
0xFF92:0x30E1,
0xFF93:0x30E2,
0xFF94:0x30E4,
0xFF95:0x30E6,
0xFF96:0x30E8,
0xFF97:0x30E9,
0xFF98:0x30EA,
0xFF99:0x30EB,
0xFF9A:0x30EC,
0xFF9B:0x30ED,
0xFF9C:0x30EF,
0xFF9D:0x30F3,
0xFF9E:0x309B,
0xFF9F:0x309C,
0xFF66:0x30F2,
65383:12449, //ァ
65384:12451, //ィ
65385:12453, //ゥ
65386:12455, //ェ
65387:12457, //ォ
65391:12483, //ッ
65388:12515, //ャ
65389:12517, //ュ
65390:12519 //ョ
};