用 JavaScript 编写自定义 URL 缩短器函数
问题
我们需要编写两个JavaScript函数-
第一个函数应该接收一个长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