简体   繁体   中英

Compress text into letters and numbers, without special characters

I want to write a tinyurl clone, and take text like:

https://myfunwebsite.com/coolthing

and shorten that string to something like:

asdf9SDFs23vbk

I have the following code:

const buffer = zlib.deflateSync(myString);
const compressed = buffer.toString('ascii');

But the problem is it creates a string like x?K())0RWOHMII/O/JIQKL??O??? which is bad for putting into url params. I want the resulting string to only be letters and numbers, how do I do this?

Um, no. Even if you didn't have to worry about arbitrary bytes in a URL, you're not going to be able to compress a short string like "https://myfunwebsite.com/coolthing". Those 34 characters will get expanded into 50 to 100 bytes by the best compressors. Lossless compressors need a lot more data than that to get rolling.

Then if you encoded it into URL-safe characters, you've expanded it by another 25% to 33%, so now you're at around 60 to 140 characters from the original 34.

This is why TinyURL doesn't work the way you seem to think it does. It does not compress. It stores the full URL on its server, and then gives you a code with which it can find that stored URL and play it back to you.

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