繁体   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