

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Preparing 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
- Related Questions & Answers
- Node.js – Base64 Encoding & Decoding
- Tips For Preparing MCSE Certification Exams
- Hard and Soft Decision Decoding
- Effective Ways of Preparing Notes for Students
- Encoding decimal to factorial and back in JavaScript
- Algorithms and Complexities
- Shortest path algorithms in Javascript
- Preparing numbers from jumbled number names in JavaScript
- URL Decoding in PHP
- Introduction to Algorithms for Mathematical Problems
- C Program for Basic Euclidean algorithms?
- C Program for Extended Euclidean algorithms?
- Python Program for Basic Euclidean algorithms
- Python Program for Extended Euclidean algorithms
- Graphs and its traversal algorithms
Advertisements