问题描述
我需要将大型UTF-8字符串转换为ASCII。它应该是可逆的,理想的是一个快/轻的算法。
I need to convert large UTF-8 strings into ASCII. It should be reversible, and ideally a quick/lightweight algorithm.
我该如何做?我需要源代码(使用循环)或 JavaScript 代码。 (不应依赖于任何平台/框架/库)
How can I do this? I need the source code (using loops) or the JavaScript code. (should not be dependent on any platform/framework/library)
修改:我理解ASCII表示形式看起来不正确,
I understand that the ASCII representation will not look correct and would be larger (in terms of bytes) than its UTF-8 counterpart, since its an encoded form of the UTF-8 original.
推荐答案
你可以使用一个ASCII版本的Douglas Crockford的json2.js quote函数。其格式如下:
You could use an ASCII-only version of Douglas Crockford's json2.js quote function. Which would look like this:
var escapable = /[\\\"\x00-\x1f\x7f-\uffff]/g,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ?
'"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' :
'"' + string + '"';
}
这将产生一个有效的ASCII,只有JavaScript的输入字符串
This will produce a valid ASCII-only, javascript-quoted of the input string
例如 Doppelgänger!)
将是Doppelg \\\änger!
e.g. quote("Doppelgänger!")
will be "Doppelg\u00e4nger!"
要还原编码,您只需评估结果
To revert the encoding you can just eval the result
var encoded = quote("Doppelgänger!");
var back = JSON.parse(encoded); // eval(encoded);
这篇关于如何将大型UTF-8字符串转换为ASCII?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!