代码之家  ›  专栏  ›  技术社区  ›  Roy Tang

从URL中删除主机名和端口的正则表达式?

  •  11
  • Roy Tang  · 技术社区  · 17 年前

    我需要编写一些javascript来从url中去掉hostname:port部分,这意味着我只想提取路径部分。

    i、 我想写一个函数getPath(url),这样getPath(“ http://host:8081/path/to/something “”)返回“/path/to/something”

    这可以用正则表达式实现吗?

    6 回复  |  直到 17 年前
        1
  •  28
  •   thirtydot    14 年前

    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
    
        2
  •  14
  •   Mike Samuel    14 年前

    我知道正则表达式很有用,但在这种情况下它们不是必需的。Location对象是DOM中所有链接的固有对象,具有pathname属性。

    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
  •  12
  •   strager    14 年前

    快速“n”脏:

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

    在第一个组中捕获主机名和端口(包括首字母/)之后的所有内容。

        4
  •  3
  •   meouw    17 年前

    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
    
        5
  •  2
  •   srikanth_k    9 年前

    很简单:

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

    正在尝试查找第二次出现的“:”,后跟数字,后跟http或https。

    前任:

    http://localhost:8080/myapplication

    https://localhost:8080/myapplication

        6
  •  1
  •   jussij    17 年前

    此正则表达式似乎有效: ( 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