Rule: The charCode of a half-width space is 32, and the charCode of a full-width space is 12288. The corresponding relationship between other half-width characters (33 – 126) and full-width characters (65281 – 65374) is: the difference is 65248.
Once you find the rules, the code will be easy to write:
var hash = {'32' : 'u3000'};
// half-width to full-width
function sbc2dbc(str) {
var ret = [], i = 0, len = str.length, code, chr;
for (; i < len; ++i) {
code = str.charCodeAt(i);
chr = hash[code];
if (!chr && code > 31 && code < 127) {
chr = hash[code] = String.fromCharCode(code + 65248);
}
ret[i] = chr ? chr : str.charAt(i);
}
return ret.join('');
}
Same reason:
var hash = {'12288' : ' '};
// Full-width to half-width
function dbc2sbc(str) {
var ret = [], i = 0, len = str.length, code, chr;
for (; i < len; ++i) {
code = str.charCodeAt(i);
chr = hash[code];
if (!chr && code > 65280 && code < 65375) {
chr = hash[code] = String.fromCharCode(code - 65248);
}
ret[i] = chr ? chr : str.charAt(i);
}
return ret.join('');
}http://qqface.knowsky.com/
The above code will also convert the symbols in the range 33 - 126. Many times, this is not what we need (such as converting @ to @). The following code is less intrusive:
var hash = {};
// Convert half-width to full-width. Convert only [0-9a-zA-Z]
function sbc2dbc_w(str) {
var ret = [], i = 0, len = str.length, code, chr;
for (; i < len; ++i) {
code = str.charCodeAt(i);
chr = hash[code];
if (!chr &&
(47 < code && code < 58 ||
64 < code && code < 91 ||
96 < code && code < 123)) {
chr = hash[code] = String.fromCharCode(code + 65248);
}
ret[i] = chr ? chr : str.charAt(i);
}
return ret.join('');
}
-