用 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
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语