2014-01-05 28 views
1

隨着幫助from this answer我的琴絃獲得乾淨的域名從URL中,如下所示:添加正則表達式規則以移除「www」。在現有的表達

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

我想刪除的子站點「WWW」(及以下點),以及儘管如果存在。我會如何改變上述表達來完成這個?

+0

一個簡單的'.replace(「WWW。 「,」「)'會工作得很好。 –

+0

也許這有助於:http://stackoverflow.com/questions/6738752/regex-for-dropping-http-and-www-from-urls – Xar

+4

@JorgeCampos當字符串「www。」會造成麻煩。出現在不同的上下文中。就像在'http:// example.com/mythoughtsaboutthewww.html'中一樣 – Philipp

回答

2

可以匹配的URL地址可選www.http://

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

你可以試試,

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

支持與不www.