使用 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
廣告