我有一个
形式的字符串[{"name":John, "title":'sir'\"SubTitle":'\gh}]
它包含所有上面提到的字符,还有一些像。等。是否有任何有效的算法/函数将此字符串转换为包含数字的数字字符串,如'34234354536564756756765745463543243',它还可以将此数字字符串解码回原始字符串?
答案 0 :(得分:3)
以下解决方案应适用于所有ASCII字符:
function encode(str) {
return str.replace(/./g, function(c) {
return ('00' + c.charCodeAt(0)).slice(-3);
});
}
function decode(str) {
return str.replace(/.{3}/g, function(c) {
return String.fromCharCode(c);
});
}
<强>测试:强>
var str = encode(JSON.stringify({ name: 'John', title: 'sir' }));
// "123034110097109101034058034074111104110034044034116105116108101034058034115105114034125"
console.log( decode(str) );
// "{"name":"John","title":"sir"}"