Reputation: 2573
I have a string in the form of
[{"name":John, "title":'sir'\"SubTitle":'\gh}]
It contains all the above mentioned characters and some more like ., etc. Is there any efficient algorithm/function to convert this string to a numeric string containing numbers like '34234354536564756756765745463543243' and it could also decode this number string back to the original string?
Upvotes: 3
Views: 2336
Reputation: 145438
The following solution should work correctly with all ASCII characters:
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);
});
}
TESTS:
var str = encode(JSON.stringify({ name: 'John', title: 'sir' }));
// "123034110097109101034058034074111104110034044034116105116108101034058034115105114034125"
console.log( decode(str) );
// "{"name":"John","title":"sir"}"
Upvotes: 6