簡體   English   中英

正則表達式從URL中刪除主機名和端口?

[英]Regular expression to remove hostname and port from URL?

我需要編寫一些javascript來從url中刪除hostname:port部分,這意味着我只想提取路徑部分。

即我想編寫一個函數getPath(url),使getPath(“ http:// host:8081 / path / to / something ”)返回“/ path / to / something”

可以使用正則表達式完成嗎?

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

我知道正則表達式很有用,但在這種情況下它們並不是必需的。 Location對象是DOM中所有鏈接的固有對象,並具有pathname屬性。

因此,要訪問某個隨機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(/^[^\/]/,'/');
}

快速'n'臟:

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

主機名和端口(包括初始/)之后的所有內容都在第一組中捕獲。

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

這很簡單:

^\w+:.*?(:)\d*

試圖找到第二次出現“:”后跟數字,然后是http或https。

這適用於以下兩種情況

例如:

HTTP://本地主機:8080 / MyApplication的

https://開頭本地主機:8080 / MyApplication的

希望這可以幫助。

這個正則表達式似乎有效: 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM