14

Are there any libraries/etc. that implement lightweight text compression in JavaScript?

My real goal is to slightly shorten some text and make it inconspicuous at a glance. (It needn't provide security -- the text will be displayed for the user.) Ideally the compression could be tweaked to output only the query characters

[-._~!$&'()*+,;=:@/?a-zA-Z0-9]

so it can be passed in a URL. (Actually, this is kind of important -- if other characters are used they'd have to be percent-encoded, which will probably make the text larger than the original.) Of course rare characters could be percent-encoded if needed.

Any ideas? Failing that, suggestions for making a simple one? The compression doesn't have to be great but shorter URLs would be nicer. The text to be compressed should be English sentences: mostly lower-case letters, spaces, and punctuation with the occasional upper-case letters, digits, and newlines.

7
  • 2
    Rather than compressing the query params, maybe you should try URL shortening services. Commented Jul 22, 2011 at 14:15
  • 2
    Compressing short text doesn't pay off much... Commented Jul 22, 2011 at 14:18
  • given that you want to compress English language sentences, and the characters in 95% or more of most sentences are included in your set of acceptable characters, you may not gain much beyond stripping whitespace. What's your motivation here? That may help determine an appropriate method. Commented Jul 22, 2011 at 14:20
  • @Ondra Žižka: Not so, considering my use case. I'd use ROT13 just for light obfuscation if I wasn't going to compress; any shortening on top of that is just a bonus. Commented Jul 22, 2011 at 15:19
  • 1
    Chrome 80 will provide CompressionStream API, see blog.chromium.org/2019/12/… Commented Dec 22, 2019 at 12:47

2 Answers 2

18

I've found lz-string which is a perfect fit for my needs. It compresses and decompresses text rapidly and can target raw bits, valid Unicode characters, or Base64. Perhaps it will be useful for someone else?

Sign up to request clarification or add additional context in comments.

1 Comment

Shall we limit the length of the compression string using this lz lib? For example, compress my long string to a short string of length 16, 32 0r 64. Is this possible here?
3

I was thinking too of a huffman compression. This javascript library is really good: http://rumkin.com/tools/compression/compress_huff.php. It has a really space saving method to compress and decompress each character. Maybe you want to look for a Golomb Code, too. It has about the same compression rate like the huffman but IMO it's easier to implement. Don't ask me about an example.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.