使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP