2009-01-14 55 views
11

我需要編寫一些JavaScript從URL中去除主機名:端口部分,這意味着我只想提取路徑部分。正則表達式從URL中刪除主機名和端口?

即我想編寫一個函數的getPath(URL),使得的getPath(「http://host:8081/path/to/something」)返回‘/路徑/到/某事’

可以這樣使用正則表達式來實現?

+0

這根本不需要正則表達式 - 請參閱我的回答:) – James 2009-01-14 09:04:44

+0

這並不是說它不需要正則表達式。這不應該使用正則表達式來完成。 – 2009-01-14 19:23:47

+0

但它仍然是有用的知道。 – 2011-02-25 15:48:50

回答

10

快速「N」髒:主機名和端口(包括初始/)後

^[^#]*?://.*?(/.*)$

一切在第一組中被捕獲。

+0

或者在正則表達式中,文字形式(「/」需要被轉義):/^.*?:\/\/./?(\/.*)$/.exec("http://example.com/文件夾/ file.ext「)[1]給出」/folder/file.ext「 – 2009-01-14 03:03:57

+2

這個正則表達式是錯誤的。它捕獲組1中的路徑,查詢和片段。 – 2009-01-14 05:20:05

1

這個正則表達式似乎工作:http://[^/] )(/

作爲測試我跑這個搜索,然後在文本編輯器替換:

Search: (http://[^/]*)(/.*) 
Replace: Part #1: \1\nPart #2: \2 

它將此文字轉換爲:

http://host:8081/path/to/something 

分解爲:

Part #1: http://host:8081 
Part #2: /path/to/something 

,並轉換此:

http://stackoverflow.com/questions/441755/regular-expression-to-remove-hostname-and-port-from-url 

成這樣:

Part #1: http://stackoverflow.com 
Part #2: /questions/441755/regular-expression-to-remove-hostname-and-port-from-url 
27

RFC 3986(http://www.ietf.org/rfc/rfc3986.txt)說,在附錄B

下面的行是用於破壞的正則表達式將 格式良好的URI引用放入其組件中。

^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? 
    12   3 4   5  6 7  8 9 

上述第二行中的數字僅用於輔助可讀性;它們指示每個子表達的參考點(即,每個配對的括號)。我們將與子表達式 匹配的值稱爲$。例如,匹配上述表達式

http://www.ics.uci.edu/pub/ietf/uri/#Related 

導致以下子表達式匹配:

$1 = http: 
    $2 = http 
    $3 = //www.ics.uci.edu 
    $4 = www.ics.uci.edu 
    $5 = /pub/ietf/uri/ 
    $6 = <undefined> 
    $7 = <undefined> 
    $8 = #Related 
    $9 = Related 

其中<undefined>指示組件不存在,因爲是 在查詢組件的情況下上面的例子。因此,我們 可以確定五個組件的價值

scheme = $2 
    authority = $4 
    path  = $5 
    query  = $7 
    fragment = $9 
13

我知道正則表達式是有用的,但他們沒有必要在這種情況下。 Location對象是DOM中所有鏈接的固有部分,並具有路徑名屬性。

因此,要訪問某個隨機URL的屬性,您可能需要創建一個新的DOM元素,然後返回其路徑名。

一個例子,這將永遠完美地工作:

function getPath(url) { 
    var a = document.createElement('a'); 
    a.href = url; 
    return a.pathname.substr(0,1) === '/' ? a.pathname : '/' + a.pathname; 
} 

jQuery的版本:(使用正則表達式來補充,如果需要斜線)

function getPath(url) { 
    return $('<a/>').attr('href',url)[0].pathname.replace(/^[^\/]/,'/'); 
} 
3

的window.location的對象有路徑,搜索和哈希屬性包含你所需要的。

本頁

location.pathname = '/questions/441755/regular-expression-to-remove-hostname-and-port-from-url' 
location.search = '' //because there is no query string 
location.hash = '' 

,所以你可以使用

var fullpath = location.pathname+location.search+location.hash