2011-02-28 65 views
4

一個快速簡單的正則表達式的問題正則表達式條域名

我,我需要剝去一個字符串有一個域名 - 總是有http://www.和領域始終處於「/

g_adv_fullpath_old = g_adv_fullpath_old.replace(/http\:\/\/www\.(.*?)\//ig, ''); 

結束我如何創建正則表達式來剝離域名?

任何幫助,將不勝感激

+0

你想用一個空字符串替換域名? – 2011-02-28 22:48:09

+0

':'不需要通過方式轉義 – 2011-02-28 23:03:03

回答

7

我就簡單的「/」分開。例如:

>>> "http://www.asdf.com/a/b/c".split("/").slice(3).join("/") 
'a/b/c' 
2

爲什麼會出現併發症?簡單indexOf會做。
首先刪除http://www(10個字符),然後在第一個斜槓之前的所有內容。

var s = "http://www.google.com/test"; 
s = s.substr(10); 
s = s.substr(s.indexOf('/')); 
alert(s); 

或者split,爲大衛建議。

An example

+1

你的意思是's.substr(s.substr(10).indexOf(「/」)+ 10)'?該確切的代碼將提醒'「le.com/test」' – 2011-02-28 22:55:14

+0

@David我的不好,謝謝你的更正。 – 2011-02-28 22:59:10

2

如果您正在尋找去除http://www.和下面的斜槓(加任何東西后)嘗試:

g_adv_fullpath_old.replace(/http:\/\/www\.(.*?)\/.*/ig, '$1') 
1

您也可以使其支撐urlParts

延長stringobject 示例

http://jsfiddle.net/stofke/Uwdha/

的Javascript

String.prototype.urlParts = function() { 
    var loc = this; 
    loc = loc.split(/([a-z0-9_\-]{1,5}:\/\/)?(([a-z0-9_\-]{1,}):([a-z0-9_\-]{1,})\@)?((www\.)|([a-z0-9_\-]{1,}\.)+)?([a-z0-9_\-]{3,})((\.[a-z]{2,4})(:(\d{1,5}))?)(\/([a-z0-9_\-]{1,}\/)+)?([a-z0-9_\-]{1,})?(\.[a-z]{2,})?(\?)?(((\&)?[a-z0-9_\-]{1,}(\=[a-z0-9_\-]{1,})?)+)?/g); 
    loc.href = this; 
    loc.protocol = loc[1]; 
    loc.user = loc[3]; 
    loc.password = loc[4]; 
    loc.subdomain = loc[5]; 
    loc.domain = loc[8]; 
    loc.domainextension = loc[10]; 
    loc.port = loc[12]; 
    loc.path = loc[13]; 
    loc.file = loc[15]; 
    loc.filetype = loc[16]; 
    loc.query = loc[18]; 
    loc.anchor = loc[22]; 
    //return the final object 
    return loc; 
}; 

用法:

var link = "http://myusername:[email protected]/a/b/c/index.php?test1=5&test2=789#tite"; 
var path = link.urlParts().path; 
var path = link.urlParts().user;