单个regexp获取页面URL,但从完整URL中排除端口号

Single regexp to get page URL but exclude port number from a full URL

本文关键字:URL 排除 口号 获取 regexp 单个      更新时间:2023-09-26

我正试图想出一个regexp来从完整的URL中获取页面URL,但从中排除一个可能的端口号。到目前为止,我想出了以下JS:

var res = url.match(/^.*':'/'/(?:www2?.)?([^?#]+)/i);
if(res)
{
    var pageURL = res[1];
    console.log(pageURL);
}

如果我这样称呼它:

var url = "http://www.example.com/php/page.php?what=sw#print";

我得到了正确的答案:example.com/php/page.php

但如果我这样做:

var url = "http://www.example.com:80/php/page.php?what=sw#print";

我需要它返回example.com/php/page.php而不是example.com:80/php/page.php

我可以用第二个regexp删除它,但我很好奇是否只用一个(为了速度)?

您可以将正则表达式修改为:

/^.*':'/'/(?:www2?.)?([^/:]+)(?:[^:]*:'d+)?([^?#]+)/i

RegEx演示

它将返回2个匹配项:

1: example.com
2: /php/page.php

分别作为两个输入的match[1]match[2],您可以连接

http://www.example.com/php/page.php?what=sw#print

http://www.example.com:80/php/page.php?what=sw#print

更新:以下是jsperf.com上的性能结果,显示regex方法是最快的

保持简单:

~ node 
> "http://www.example.com:3000/php/page.php?what=sw#print".replace(/:'d+/, '');
'http://www.example.com/php/page.php?what=sw#print'
> "http://www.example.com/php/page.php?what=sw#print".replace(/:'d+/, '');
'http://www.example.com/php/page.php?what=sw#print'

为什么要使用正则表达式?


编辑:

正如@c00000fd所指出的:因为document可能不可用,并且document.createElement与RegExp相比非常慢-请参阅:

http://jsperf.com/url-parsing/5

http://jsperf.com/hostname-from-url

不过,我会留下我原来的答案,以供参考。


原始答案:

相反,您可以只使用Anchor元素:

Fiddle:

http://jsfiddle.net/12qjqx7n/

JS:

var url = 'http://foo:bar@www.example.com:8080/php/page.php?what=sw#print'
var a = document.createElement('a');
a.href = url;
console.log(a.hash);
console.log(a.host);
console.log(a.hostname);
console.log(a.origin);
console.log(a.password);
console.log(a.pathname);
console.log(a.port);
console.log(a.protocol);
console.log(a.search);
console.log(a.username);

附加信息:

http://www.w3schools.com/jsref/dom_obj_anchor.asp

如果存在匹配端口的组,那么如何?

var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.match(/^.*':'/'/(?:www2?.)?([^?#'/:]+)(':'d+)?('/[^?#]+)/i);
if(res)
{
    var pageURL = res[1]+res[3];
    console.log(res, pageURL);
}

尝试

var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.split(/'w+:'/'/+'w+'.|:+'d+|'?.*/).join("");

var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.split(/'w+:'/'/+'w+'.|:+'d+|'?.*/).join("");
document.body.innerText = res;

您可以使用replace方法修改原始字符串或Url,

> var url = "http://www.example.com/php/page.php?what=sw#print";
undefined
> var url1 = "http://www.example.com:80/php/page.php?what=sw#print";
undefined
> url.replace(/^.*?:'/'/(?:www2?.)?([^/:]+)(?::'d+)?([^?#]+).*$/g, "$1$2")
'example.com/php/page.php'
> url1.replace(/^.*?:'/'/(?:www2?.)?([^/:]+)(?::'d+)?([^?#]+).*$/g, "$1$2")
'example.com/php/page.php'

演示