简体   繁体   中英

String to number and then back to string encryption/decryption in JavaScript

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?

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"}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM