最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Parsing url in javascript or angularjs - Stack Overflow

programmeradmin5浏览0评论

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

var getLocation = function(href) {
    var l = document.createElement("a");
    l.href = href;
    return l;
};
var l = getLocation(":3000/path");
var host = l.host; // example
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?

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

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?

Share Improve this question asked Jan 14, 2015 at 10:05 Ramzy AbourafehRamzy Abourafeh 1,1957 gold badges18 silver badges35 bronze badges 3
  • Try doing l.hostname – aug Commented Jan 14, 2015 at 10:07
  • james.padolsey.com/javascript/parsing-urls-with-the-dom – smarber Commented Jan 14, 2015 at 10:09
  • IF you have the url already, wouldn't you be better to split() and get the components? (Rather then create an object I mean) If there any perf benefits of doing it this way rather then using strings? – atmd Commented Jan 14, 2015 at 10:09
Add a comment  | 

2 Answers 2

Reset to default 14

Source:- 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"

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

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

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

> 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.

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

发布评论

评论列表(0)

  1. 暂无评论