Basic usageVery simple:
- First, download the file lz-string-1.3.0.js from the GitHub repository.
- At last, call compress and decompress on the LZString object:
var string = "This is my compression test."; alert("Size of sample is: " + string.length); var compressed = LZString.compress(string); alert("Size of compressed sample is: " + compressed.length); string = LZString.decompress(compressed); alert("Sample is: " + string);
Storing compressed data into localStorageOn Firefox and IE, localStorage cannot contain invalid UTF16 characters. So you will need the following:
Sending compressed data outside the browserlz-string is meant for storage in a string-based storage system. This means something like localStorage is the ideal place. If you need to compress data to send it to a server, the output of lz-string is not ideal.
Two methods compressToEncodedURIComponent and decompressFromEncodedURIComponent (in lz-string 1.3.5 and above - before that you had to use compressToBase64 and decompressFromBase64 which are not exactly URI compliant) are there for this very purpose. Note that this method produce strings that are 2.7 times bigger than compress since all it does is encoding the result in base64.
Compressing base64 inputIt works out of the box, but... but there is a catch: Often, we use base64 to encode binary content, which may or may not be already compressed. LZW has a tendency of producing output files that are bigger than the input file for files already compressed. Hence, using lz-string on such an encoded binary file will not be optimal. From experiment, it produces an output that is most often than not bigger than the original binary file.
base64-string-v1.1.0.js was released to address this concern. It decodes the base64 input into a string where all 16-bits are used as storage, getting an output of the size of the original. In this case, it compresses better than lz-string while being a lot faster.
WARNING: since storing stuff in strings means storing in a 16-bit word space, I have to add a parity bit at the beginning of the string for the decompressor to know if the last character should be considered as 2 bytes or one byte with padding. So don't use this lib for anything else than compressing/decompressing. In other words, its output is something the resembles the original file but is garbled nonetheless and meaningless for anything but the decompress routine.
Note that this doesn't really compress anything, it just reencodes it. By doing so it produces a "compressed" version that is always 2.7 times smaller than the input (16/6).