我正试图想出一个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'
演示