Writing a custom URL shortener function in JavaScript

URL shorteners convert long URLs into shorter, more manageable links. This tutorial shows how to build a simple URL shortener with JavaScript functions for encoding and decoding URLs.

Problem Statement

We need to create two JavaScript functions:

  • First function takes a long URL and returns a corresponding short URL
  • Second function takes the short URL and returns the original long URL

How It Works

Our approach uses an object to store mappings between short and long URLs. The short URL is generated by extracting letters from the original URL and taking the last 4 characters.

Long URL example.com/very/long/path URL Shortener Extract & Store Short URL short.ly/path Storage Object {"short.ly/path": "long_url"}

Implementation

const url = 'https://www.google.com/search?client=firefox-b-d&q=google+search';
const obj = {};

const urlShortener = (longURL = '') => {
    let shortURL = "short.ly/" + longURL.replace(/[^a-z]/g,'').slice(-4);
    if(!obj[shortURL]){
        obj[shortURL] = longURL;
    };
    return shortURL;
}

const urlRedirector = (shortURL = '') => {
    return obj[shortURL];
};

const short = urlShortener(url);
const original = urlRedirector(short);
console.log('Short URL:', short);
console.log('Original URL:', original);

Output

Short URL: short.ly/arch
Original URL: https://www.google.com/search?client=firefox-b-d&q=google+search

How the Algorithm Works

The shortening process involves these steps:

  1. Extract letters: replace(/[^a-z]/g,'') removes all non-lowercase letters
  2. Take last 4 chars: slice(-4) gets the final 4 characters
  3. Create short URL: Prepend "short.ly/" to create the final short URL
  4. Store mapping: Save the relationship in the object for later retrieval

Enhanced Version with Collision Handling

const urlDatabase = {};
let counter = 1000;

const createShortUrl = (longURL) => {
    // Check if URL already exists
    for (let key in urlDatabase) {
        if (urlDatabase[key] === longURL) {
            return key;
        }
    }
    
    // Generate unique short URL
    let shortURL;
    do {
        shortURL = "short.ly/" + (counter++).toString(36);
    } while (urlDatabase[shortURL]);
    
    urlDatabase[shortURL] = longURL;
    return shortURL;
};

const expandShortUrl = (shortURL) => {
    return urlDatabase[shortURL] || 'URL not found';
};

// Test the enhanced version
const testUrl = 'https://www.tutorialspoint.com/javascript/index.htm';
const shortened = createShortUrl(testUrl);
const expanded = expandShortUrl(shortened);

console.log('Original:', testUrl);
console.log('Shortened:', shortened);
console.log('Expanded:', expanded);
Original: https://www.tutorialspoint.com/javascript/index.htm
Shortened: short.ly/rs
Expanded: https://www.tutorialspoint.com/javascript/index.htm

Key Features

  • Collision Prevention: Uses counter-based generation to avoid duplicates
  • Duplicate Detection: Prevents creating multiple short URLs for the same long URL
  • Error Handling: Returns appropriate message for non-existent URLs
  • Base36 Encoding: Creates compact, alphanumeric short codes

Conclusion

This URL shortener demonstrates core JavaScript concepts including regular expressions, object storage, and string manipulation. The enhanced version adds collision handling for production-ready functionality.

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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements