用 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 官宣新年祝福语简短