gpt4 book ai didi

javascript - 更正正则表达式以删除 www. & .com 等来自 url Javascript

转载 作者:行者123 更新时间:2023-12-03 03:08:25 26 4
gpt4 key购买 nike

我似乎找不到转弯的方法

var testString = "www.example.com"; 

进入

"example"

我正在尝试使用正则表达式来实现此目的。我可以使用 .replace 等来完成,但我想知道如何使用正确的正则表达式。

最佳答案

function getHostName(url) {
var match = url.match(/:\/\/(www[0-9]?\.)?(.[^/:]+)/i);
if (match != null && match.length > 2 && typeof match[2] === 'string' && match[2].length > 0) {
var hostname = match[2].split(".");
return hostname[0];
}
else {
return null;
}
}

var url1 = "http://www.example.co.uk/foo/bar?hat=bowler&accessory=cane";
var url2 = "https://stackoverflow.com/questions/47059759/";
var url3 = "http://www.example.com/?q=keyword";
console.log( getHostName(url1) );
console.log( getHostName(url2) );
console.log( getHostName(url3) );

关于javascript - 更正正则表达式以删除 www. & .com 等来自 url Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47059759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com