使用 JavaScript 編寫一個自定義 URL 縮短函式


問題

我們需要編寫兩個 JavaScript 函式 −

  • 第一個函式應接收一個長 URL 並返回與其對應的短 URL。
  • 第二個函式應接收短 URL 並重定向到原始 URL。

示例

以下是程式碼 −

 即時演示

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);
console.log(original);

輸出

以下是控制檯輸出 −

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

更新於: 20-Apr-2021

2K+ 瀏覽

職業生涯 起航

完成課程認證

開始學習
廣告