Javascript 添加正则表达式规则以删除;www;论存在表达

Javascript 添加正则表达式规则以删除;www;论存在表达,javascript,regex,Javascript,Regex,在帮助下,我可以从URL字符串中获得干净的域名,如下所示: url = "http://www.stackoverflow.com/questions/ask" var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i); return matches ? matches[1] : url; >> "www.stackoverflow.com" 我想删除子域“www”(和下面的点),如果存在的话。如何更改上

在帮助下,我可以从URL字符串中获得干净的域名,如下所示:

url = "http://www.stackoverflow.com/questions/ask"  
var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);  
return matches ? matches[1] : url;
>> "www.stackoverflow.com"
我想删除子域“www”(和下面的点),如果存在的话。如何更改上述表达式以实现此目的?

您可以尝试

url = "http://www.stackoverflow.com/questions/ask"  
var matches = url.match(/^https?\:\/\/(www\.)?([^\/?#]+)(?:[\/?#]|$)/i);  
return matches ? matches[2] : url;

要支持包含和不包含
www.
的url地址,您可以在
http://
之后匹配可选的
www.

var matches = url.match(/^https?\:\/\/(?:www\.)?([^\/?#]+)(?:[\/?#]|$)/i);
//=> ["http://www.stackoverflow.com/", "stackoverflow.com"]

一个简单的
.replace(“www.,”)
就可以了。也许这会有帮助:@JorgeCampos,当字符串“www.”出现在不同的上下文中时,会引起麻烦。喜欢
http://example.com/mythoughtsaboutthewww.html