Preparing encoding and decoding algorithms for shortening URLs in JavaScript

URL shortening services like bit.ly and TinyURL take long URLs and convert them into shorter, more manageable links. This process involves encoding the original URL into a compact format and later decoding it back when accessed.

To implement a basic URL shortening system in JavaScript, we need two main functions:

  • encrypt() ? takes the original URL and returns a shortened unique URL

  • decrypt() ? takes the shortened URL and converts it back to the original URL

Basic Implementation Using Base64 Encoding

Here's a simple approach using Base64 encoding with Node.js Buffer:

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("Shortened URL:", encrypted);
console.log("Original URL:", decrypted);
Shortened URL: http://mydemo.com/aHR0cHM6Ly9kZXZlbG9wZXIubW96aWxsYS5vcmcvZW4tVVMvZG9jcy9XZWIvSmF2YVNjcmlwdA==
Original URL: https://developer.mozilla.org/en-US/docs/Web/JavaScript

Browser-Compatible Version

For client-side JavaScript without Node.js Buffer, use the built-in btoa() and atob() functions:

<script>
const url = 'https://www.tutorialspoint.com/javascript/index.htm';

const encryptUrl = (longUrl) => {
    const encoded = btoa(longUrl);
    return "http://short.ly/" + encoded;
};

const decryptUrl = (shortUrl) => {
    const encoded = shortUrl.split('short.ly/')[1];
    return atob(encoded);
};

const shortened = encryptUrl(url);
const original = decryptUrl(shortened);

console.log("Shortened:", shortened);
console.log("Original:", original);
</script>

Enhanced Version with Error Handling

const urlShortener = {
    baseUrl: "https://short.ly/",
    
    encrypt: function(longUrl) {
        try {
            if (!longUrl || typeof longUrl !== 'string') {
                throw new Error('Invalid URL provided');
            }
            const encoded = Buffer.from(longUrl).toString('base64url');
            return this.baseUrl + encoded;
        } catch (error) {
            return `Error: ${error.message}`;
        }
    },
    
    decrypt: function(shortUrl) {
        try {
            if (!shortUrl.includes(this.baseUrl)) {
                throw new Error('Invalid short URL format');
            }
            const encoded = shortUrl.split(this.baseUrl)[1];
            return Buffer.from(encoded, 'base64url').toString();
        } catch (error) {
            return `Error: ${error.message}`;
        }
    }
};

// Test the enhanced version
const testUrl = 'https://www.example.com/very/long/path/to/resource';
const shortened = urlShortener.encrypt(testUrl);
const restored = urlShortener.decrypt(shortened);

console.log("Original:", testUrl);
console.log("Shortened:", shortened);
console.log("Restored:", restored);
Original: https://www.example.com/very/long/path/to/resource
Shortened: https://short.ly/aHR0cHM6Ly93d3cuZXhhbXBsZS5jb20vdmVyeS9sb25nL3BhdGgvdG8vcmVzb3VyY2U
Restored: https://www.example.com/very/long/path/to/resource

Key Points

  • Base64 Encoding: Converts binary data to ASCII string format, making URLs web-safe

  • Reversible Process: Base64 encoding is reversible, allowing perfect URL restoration

  • Not True Shortening: Base64 often increases length rather than shortening it

  • Production Considerations: Real services use hash functions and databases for true shortening

Limitations of This Approach

While this method demonstrates the encoding/decoding concept, it has limitations:

  • Base64 encoding typically makes URLs longer, not shorter
  • Real URL shorteners use hash algorithms combined with database lookups
  • No collision detection or uniqueness guarantees

Conclusion

This basic implementation shows the fundamental concept behind URL shortening using encoding and decoding. Production systems use more sophisticated algorithms with hash functions and databases to achieve true URL shortening while maintaining uniqueness and performance.

Updated on: 2026-03-15T23:19:00+05:30

920 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements