简体   繁体   中英

Javascript LZ String compression check if string is already compressed

I am using the LZ String library https://github.com/pieroxy/lz-string/ to compress/decompress strings and save them in localStorage.

Since the compression is going to be applied on an existing project having customers with uncompressed strings already saved on localStorage. Is there a way to know if saved string is already compressed?

Sometimes when you try to decompress an uncompressed string you get Null or an empty string but some characters still are "wrongly" decompressed. For example:

LZString.decompressFromUTF16("O"); //returns null
LZString.decompressFromUTF16("J"); //returns string 0x80

Also if I try to decompress the word Jam I don't get a Null or empty result just a string;

LZString.decompressFromUTF16("Jam"); //returns string 0x80

Here is a JsFiddle with an example https://jsfiddle.net/imurphy/8c94mhxw/

Any ideas? Thanks

I think a better structured alternative would be to save the compressed strings in such a format that you can easily detect whether it's compressed or not. For example, rather than doing:

localStorage.property = someCompressedString;

do something like

localStorage.property = JSON.stringify({ compressed: true, payload: someCompressedString });
// or, if there isn't a chance of collisions with the following approach:
localStorage.property = 'compressed-true---' + someCompressedString;

and then check if the value is JSON-parseable or starts with compressed-true--- , and extract the compressed string part as needed.

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