Clark To Do The blog of Clark

ASCII, Unicode 汉字转换

首先, 将汉字转换为 ASCII 的函数:

function ascii(str) {
    return str.replace(/[^\u0000-\u00FF]/g, function($0) {
        return escape($0).replace(/(%u)(\w{4})/gi, "\&#x$2;")
    });
}

接下来, 是将汉字转换为 Unicode 的函数:

function unicode(str) {
    return str.replace(/[^\u0000-\u00FF]/g, function($0) {
        return escape($0).replace(/(%u)(\w{4})/gi, "\\u$2")
    });
}

最后. 是将ASCII, Unicode反向转换为汉字的函数:

function reconvert(str) {
    str = str.replace(/(\\u)(\w{4})/gi, function($0) {
        return (String.fromCharCode(parseInt((escape($0).replace(/(%5Cu)(\w{4})/g, "$2")), 16)));
    });
    str = str.replace(/(&#x)(\w{4});/gi, function($0) {
        return String.fromCharCode(parseInt(escape($0).replace(/(%26%23x)(\w{4})(%3B)/g, "$2"), 16));
    });
    return str;
}
comments powered by Disqus