
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Encoding and Decoding Algorithms for Shortening URLs in JavaScript
We often come through services like bit.ly and tinyurl which takes in any url and (usually one bigger in length), performs some encryption algorithm over it and returns a very short url. And similarity when we try to open that tiny url, it again runs some decryption algorithm over it and converts the short url to the original one opens the link for us.
We are also required to perform the same task. We are actually required to write two functions −
encrypt() --> it will take in the original url and return to us a short unique ur.
decrypt() --> it will take in the short url, will have no prior idea about the original url and convert it to the original url.
Example
The code for this will be −
const url = 'https://developer.mozilla.org/en-US/docs/Web/JavaScript'; const encrypt = (longUrl) => { const encodedUrl = Buffer.from(longUrl, 'binary').toString('base64'); return "http://mydemo.com/" + encodedUrl; }; const decrypt = function(shortUrl) { let encodedUrl = shortUrl.split('mydemo.com/')[1]; return Buffer.from(encodedUrl, 'base64').toString(); }; const encrypted = encrypt(url); const decrypted = decrypt(encrypted); console.log(encrypted); console.log(decrypted);
Output
And the output in the console will be −
http://mydemo.com/aHR0cHM6Ly9kZXZlbG9wZXIubW96aWxsYS5vcmcvZW4tVVMvZG9jcy9XZWIvSmF2YVNjcmlwdA== https://developer.mozilla.org/en-US/docs/Web/JavaScript
Advertisements