在 javascript 或 angularjs 中解析 url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27940283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:11:56  来源:igfitidea点击:

Parsing url in javascript or angularjs

javascriptangularjsparsingurl

提问by Ramzy Abourafeh

I'm trying to parse url in javascript, I found the following way:

我正在尝试在 javascript 中解析 url,我找到了以下方法:

var getLocation = function(href) {
    var l = document.createElement("a");
    l.href = href;
    return l;
};
var l = getLocation("http://example.com:3000/path");
var host = l.host; // example.com
var port = l.port; // 3000

But I faced a problem if these locations:

但是,如果这些位置,我会遇到问题:

http://TLVS0015:3000/cti/YTest // the parse found the port, but its not found the host

http://ctmwe:80/ReportServer/ReportService2010.asmx // the parse found the host, but don't found the port

Is there any other way to do the parse?

有没有其他方法可以进行解析?

回答by squiroid

Source:- https://gist.github.com/jlong/2428561

来源:- https://gist.github.com/jlong​​/2428561

var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";

parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port;     // => "3000"
parser.pathname; // => "/pathname/"
parser.search;   // => "?search=test"
parser.hash;     // => "#hash"
parser.host;     // => "example.com:3000"

回答by Bas Dirks

If you don't need to support Internet Explorer (http://caniuse.com/#feat=url), use URL. Use hostnameinstead of host.

如果您不需要支持 Internet Explorer ( http://caniuse.com/#feat=url),请使用URL. 使用hostname代替host

> new URL("http://TLVS0015:3000/cti/YTest").hostname
tlvs0015

The port is 80. Port 80 is default, so it is redundant, hence "".

端口是 80。端口 80 是默认的,所以它是多余的,因此"".

> new URL("http://ctmwe:80/ReportServer/ReportService2010.asmx").port
""

port = URL.port === "" ? 80 : URL.port

For more information on URL(), consult the MDN API documents.

有关更多信息URL()请参阅 MDN API 文档

Note: as of July 2017, URLis not supported by Internet Explorer 11: http://caniuse.com/#feat=url

注意:截至 2017 年 7 月,URLInternet Explorer 11 不支持http: //caniuse.com/#feat=url