有人问到那就写个简单的方法吧
方法一:可以使用JavaScript的字符串截取方法来提取链接中的主机名,然后将其用作URL的基础,加上斜杠即可。
addSlashToUrl() {
const url = 'https://www.baidu.com/?from=2001l';
const hostname = new URL(url).hostname; // 提取主机名
const urlWithSlash = `https://${hostname}/`; // 加上斜杠
console.log(urlWithSlash); // 输出 https://www.baidu.com/
}
方法二:可以使用正则
function addSlashToUrl(url) {
const regex = /^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n?]+)/gim;
const hostname = regex.exec(url)[1];
return `https://${hostname}/`;
}
// 例子
console.log(addSlashToUrl('https://www.baidu.com/?from=2001l')); // 输出 https://www.baidu.com/
方法三:使用DOM API来解析URL并获取主机名:
function addSlashToUrl(url) {
const link = document.createElement('a');
link.href = url;
const hostname = link.hostname;
return `https://${hostname}/`;
}
// 例子
console.log(addSlashToUrl('https://www.baidu.com/?from=2001l')); // 输出 https://www.baidu.com/