Vấn đề
Chúng ta cần viết hai hàm JavaScript:
- Hàm đầu tiên nhận vào một URL dài và trả về một URL ngắn tương ứng.
- Hàm thứ hai nhận vào URL ngắn và chuyển hướng về URL gốc.
Ví dụ
Dưới đây là mã:
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);
Kết quả
Kết quả console:
short.ly/arch https://www.google.com/search?client=firefox-b-d&q=google+search