Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,939 questions

51,876 answers

573 users

How to write a custom URL shortener in TypeScript

1 Answer

0 votes
// Object to store URL mappings
const urlDatabase: Record<string, string> = {};

// Function to generate a random short code
function generateShortCode(): string {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let shortCode: string = '';

  for (let i: number = 0; i < 8; i++) {
    shortCode += characters.charAt(Math.floor(Math.random() * characters.length));
  }

  return shortCode;
}

// Function to shorten a URL
function shortenURL(longURL: string): string {
  const shortCode: string = generateShortCode();
  
  urlDatabase[shortCode] = longURL;

  return `https://short.url/${shortCode}`;
}

// Function to retrieve the long URL
function getLongURL(shortURL: string): string {
  const shortCode: string | undefined = shortURL.split('/').pop();

  if (!shortCode) return 'Invalid short URL!';

  return urlDatabase[shortCode] || 'URL not found!';
}

const longURL: string = 'https://www.seek4info.com/search.php?query=printf';
const shortURL: string = shortenURL(longURL);
console.log('Shortened URL:', shortURL);

const retrievedLongURL: string = getLongURL(shortURL);
console.log('Retrieved URL:', retrievedLongURL);



/*
run:

"Shortened URL:",  "https://short.url/xDAGLfNv" 
"Retrieved URL:",  "https://www.seek4info.com/search.php?query=printf" 

*/

 



answered Sep 27, 2025 by avibootz
...