从URL获取协议、域和端口

时间:2021-08-26 18:13:17

I need to extract the full protocol, domain, and port from a given URL. For example:

我需要从给定的URL中提取完整的协议、域和端口。例如:

https://localhost:8181/ContactUs-1.0/contact?lang=it&report_type=consumer
>>>
https://localhost:8181

12 个解决方案

#1


102  

first get the current address

首先获取当前地址

var url = window.location.href

Then just parse that string

然后解析这个字符串

var arr = url.split("/");

your url is:

你的网址是:

var result = arr[0] + "//" + arr[2]

Hope this helps

希望这有助于

#2


444  

var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');

#3


123  

None of these answers seem to completely address the question, which calls for an arbitrary url, not specifically the url of the current page.

这些答案似乎都不能完全解决这个问题,这个问题需要一个任意的url,而不是当前页面的url。

Method 1: Use the URL API (caveat: no IE11 support)

You can use the URL API (not supported by IE11, but available everywhere else).

您可以使用URL API (IE11不支持,但在其他任何地方都可以使用)。

This also makes it easy to access search params. Another bonus: it can be used in a Web Worker since it doesn't depend on the DOM.

这也使得访问搜索参数很容易。另一个好处是:它可以在Web Worker中使用,因为它不依赖于DOM。

const url = new URL('http://example.com:12345/blog/foo/bar?startIndex=1&pageSize=10');

Method 2 (old way): Use the browser's built-in parser in the DOM

Use this if you need this to work on older browsers as well.

如果您需要在旧的浏览器上使用它,也可以使用它。

//  Create an anchor element (note: no need to append this element to the document)
const url = document.createElement('a');
//  Set href to any path
url.setAttribute('href', 'http://example.com:12345/blog/foo/bar?startIndex=1&pageSize=10');

That's it!

The browser's built-in parser has already done its job. Now you can just grab the parts you need (note that this works for both methods above):

浏览器的内置解析器已经完成了它的工作。现在你可以只抓取你需要的部分(注意,以上两种方法都适用):

//  Get any piece of the url you're interested in
url.hostname;  //  'example.com'
url.port;      //  12345
url.search;    //  '?startIndex=1&pageSize=10'
url.pathname;  //  '/blog/foo/bar'
url.protocol;  //  'http:'

Bonus: Search params

Chances are you'll probably want to break apart the search url params as well, since '?startIndex=1&pageSize=10' isn't too useable on its own.

你可能会想要分开搜索url的参数,因为?startIndex=1&pageSize=10'本身不是很有用。

If you used Method 1 (URL API) above, you simply use the searchParams getters:

如果您使用上述方法1 (URL API),您只需使用searchParams getter:

url.searchParams.get('searchIndex');  // '1'

Or to get all parameters:

或获取所有参数:

Array.from(url.searchParams).reduce((accum, [key, val]) => {
  accum[key] = val;
  return accum;
}, {});
// -> { startIndex: '1', pageSize: '10' }

If you used Method 2 (the old way), you can use something like this:

如果您使用方法2(旧的方法),您可以使用如下内容:

// Simple object output (note: does NOT preserve duplicate keys).
var parms = url.search.substr(1); // remove '?' prefix
params.split('&').reduce((accum, keyval) => {
  const [key, val] = keyval.split('=');
  accum[key] = val;
  return accum;
}, {});
// -> { startIndex: '1', pageSize: '10' }

#4


104  

For some reason all the answers are all overkills. This is all it takes:

由于某种原因,所有的答案都是多余的。这就是所需要的:

window.location.origin

More details can be found here: https://developer.mozilla.org/en-US/docs/Web/API/window.location#Properties

更多细节可以在这里找到:https://developer.mozilla.org/en-US/docs/Web/API/window.location#Properties

#5


45  

As has already been mentioned there is the as yet not fully supported window.location.origin but instead of either using it or creating a new variable to use, I prefer to check for it and if it isn't set to set it.

正如已经提到的,目前还没有完全支持windows .location。但不是使用它或者创建一个新的变量来使用,我更喜欢检查它,如果它没有设置为设置它。

For example;

例如;

if (!window.location.origin) {
  window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}

I actually wrote about this a few months back A fix for window.location.origin

几个月前,我写了一个windows。location。origin的修正

#6


26  

host

主机

var url = window.location.host;

returns localhost:2679

返回localhost:2679

hostname

主机名

var url = window.location.hostname;

returns localhost

返回本地主机

#7


10  

The protocol property sets or returns the protocol of the current URL, including the colon (:).

协议属性设置或返回当前URL的协议,包括冒号(:)。

This means that if you want to get only the HTTP/HTTPS part you can do something like this:

这意味着,如果您只想获得HTTP/HTTPS部分,可以执行以下操作:

var protocol = window.location.protocol.replace(/:/g,'')

For the domain you can use:

你可使用的域名:

var domain = window.location.hostname;

For the port you can use:

对于您可以使用的端口:

var port = window.location.port;

Keep in mind that the port will be an empty string if it is not visible in the URL. For example:

请记住,如果该端口在URL中不可见,则该端口将是一个空字符串。例如:

If you need to show 80/443 when you have no port use

如果在没有端口使用时需要显示80/443

var port = window.location.port || (protocol === 'https' ? '443' : '80');

#8


5  

Indeed, window.location.origin works fine in browsers following standards, but guess what. IE isn't following standards.

事实上,window.location。origin在遵循标准的浏览器中工作得很好,但是你猜怎么着。即不遵循的标准。

So because of that, this is what worked for me in IE, FireFox and Chrome:

正因为如此,这就是我在IE,火狐和Chrome中的应用:

var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');

but for possible future enhancements which could cause conflicts, I specified the "window" reference before the "location" object.

但是,对于将来可能导致冲突的增强,我在“location”对象之前指定了“window”引用。

var full = window.location.protocol+'//'+window.location.hostname+(window.location.port ? ':'+window.location.port: '');

#9


2  

var http = location.protocol;
var slashes = http.concat("//");
var host = slashes.concat(window.location.hostname);

#10


2  

var getBasePath = function(url) {
    var r = ('' + url).match(/^(https?:)?\/\/[^/]+/i);
    return r ? r[0] : '';
};

#11


2  

Try use a regular expression (Regex), which will be quite useful when you want to validate / extract stuff or even do some simple parsing in javascript.

尝试使用正则表达式(Regex),当您想要验证/提取内容,甚至在javascript中执行一些简单的解析时,它将非常有用。

The regex is :

正则表达式是:

/([a-zA-Z]+):\/\/([\-\w\.]+)(?:\:(\d{0,5}))?/

Demonstration:

演示:

function breakURL(url){

     matches = /([a-zA-Z]+):\/\/([\-\w\.]+)(?:\:(\d{0,5}))?/.exec(url);

     foo = new Array();

     if(matches){
          for( i = 1; i < matches.length ; i++){ foo.push(matches[i]); }
     }

     return foo
}

url = "https://www.google.co.uk:55699/search?q=http%3A%2F%2F&oq=http%3A%2F%2F&aqs=chrome..69i57j69i60l3j69i65l2.2342j0j4&sourceid=chrome&ie=UTF-8"


breakURL(url);       // [https, www.google.co.uk, 55699] 
breakURL();          // []
breakURL("asf");     // []
breakURL("asd://");  // []
breakURL("asd://a"); // [asd, a, undefined]

Now you can do validation as well.

现在您还可以进行验证。

#12


1  

David's answer is great and very comprehensive but won't work with server side javascript because of the document.createElement calls (document won't be defined).

David的回答非常全面,但是由于文档的原因,无法使用服务器端javascript。createElement调用(文档不会被定义)。

I wrote a simple component that covers arbitrary urls on the server or within a browser and parses them into an object. You can use parseUrl() as follows to get the base url and port without the path or query string:

我编写了一个简单的组件,该组件涵盖服务器或浏览器中的任意url,并将它们解析为对象。您可以使用parseUrl()来获取基本url和没有路径或查询字符串的端口:

var url = 'https://localhost:8181/ContactUs-1.0/contact?lang=it&report_type=consumer';
var urlObject = parseUrl(url);
var newUrl = urlObject.protocol + '//' + urlObject.host;

Like David's method, this also provides all of the pieces of the url within the url object.

与David的方法一样,它还提供url对象中url的所有部分。

urlObject.href         // 'https://localhost:8181/ContactUs-1.0/contact?lang=it&report_type=consumer'
urlObject.searchParams // { lang: 'it', report_type: 'consumer' }
urlObject.hash         // ''
urlObject.search       // '?lang=it&report_type=consumer'
urlObject.protocol     // 'https:'
urlObject.host         // 'localhost:8181'
urlObject.hostname     // 'localhost'
urlObject.path         // '/ContactUs-1.0/contact'

Feel free to import the component to use the parseUrl method.

请随意导入组件以使用parseUrl方法。

#1


102  

first get the current address

首先获取当前地址

var url = window.location.href

Then just parse that string

然后解析这个字符串

var arr = url.split("/");

your url is:

你的网址是:

var result = arr[0] + "//" + arr[2]

Hope this helps

希望这有助于

#2


444  

var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');

#3


123  

None of these answers seem to completely address the question, which calls for an arbitrary url, not specifically the url of the current page.

这些答案似乎都不能完全解决这个问题,这个问题需要一个任意的url,而不是当前页面的url。

Method 1: Use the URL API (caveat: no IE11 support)

You can use the URL API (not supported by IE11, but available everywhere else).

您可以使用URL API (IE11不支持,但在其他任何地方都可以使用)。

This also makes it easy to access search params. Another bonus: it can be used in a Web Worker since it doesn't depend on the DOM.

这也使得访问搜索参数很容易。另一个好处是:它可以在Web Worker中使用,因为它不依赖于DOM。

const url = new URL('http://example.com:12345/blog/foo/bar?startIndex=1&pageSize=10');

Method 2 (old way): Use the browser's built-in parser in the DOM

Use this if you need this to work on older browsers as well.

如果您需要在旧的浏览器上使用它,也可以使用它。

//  Create an anchor element (note: no need to append this element to the document)
const url = document.createElement('a');
//  Set href to any path
url.setAttribute('href', 'http://example.com:12345/blog/foo/bar?startIndex=1&pageSize=10');

That's it!

The browser's built-in parser has already done its job. Now you can just grab the parts you need (note that this works for both methods above):

浏览器的内置解析器已经完成了它的工作。现在你可以只抓取你需要的部分(注意,以上两种方法都适用):

//  Get any piece of the url you're interested in
url.hostname;  //  'example.com'
url.port;      //  12345
url.search;    //  '?startIndex=1&pageSize=10'
url.pathname;  //  '/blog/foo/bar'
url.protocol;  //  'http:'

Bonus: Search params

Chances are you'll probably want to break apart the search url params as well, since '?startIndex=1&pageSize=10' isn't too useable on its own.

你可能会想要分开搜索url的参数,因为?startIndex=1&pageSize=10'本身不是很有用。

If you used Method 1 (URL API) above, you simply use the searchParams getters:

如果您使用上述方法1 (URL API),您只需使用searchParams getter:

url.searchParams.get('searchIndex');  // '1'

Or to get all parameters:

或获取所有参数:

Array.from(url.searchParams).reduce((accum, [key, val]) => {
  accum[key] = val;
  return accum;
}, {});
// -> { startIndex: '1', pageSize: '10' }

If you used Method 2 (the old way), you can use something like this:

如果您使用方法2(旧的方法),您可以使用如下内容:

// Simple object output (note: does NOT preserve duplicate keys).
var parms = url.search.substr(1); // remove '?' prefix
params.split('&').reduce((accum, keyval) => {
  const [key, val] = keyval.split('=');
  accum[key] = val;
  return accum;
}, {});
// -> { startIndex: '1', pageSize: '10' }

#4


104  

For some reason all the answers are all overkills. This is all it takes:

由于某种原因,所有的答案都是多余的。这就是所需要的:

window.location.origin

More details can be found here: https://developer.mozilla.org/en-US/docs/Web/API/window.location#Properties

更多细节可以在这里找到:https://developer.mozilla.org/en-US/docs/Web/API/window.location#Properties

#5


45  

As has already been mentioned there is the as yet not fully supported window.location.origin but instead of either using it or creating a new variable to use, I prefer to check for it and if it isn't set to set it.

正如已经提到的,目前还没有完全支持windows .location。但不是使用它或者创建一个新的变量来使用,我更喜欢检查它,如果它没有设置为设置它。

For example;

例如;

if (!window.location.origin) {
  window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}

I actually wrote about this a few months back A fix for window.location.origin

几个月前,我写了一个windows。location。origin的修正

#6


26  

host

主机

var url = window.location.host;

returns localhost:2679

返回localhost:2679

hostname

主机名

var url = window.location.hostname;

returns localhost

返回本地主机

#7


10  

The protocol property sets or returns the protocol of the current URL, including the colon (:).

协议属性设置或返回当前URL的协议,包括冒号(:)。

This means that if you want to get only the HTTP/HTTPS part you can do something like this:

这意味着,如果您只想获得HTTP/HTTPS部分,可以执行以下操作:

var protocol = window.location.protocol.replace(/:/g,'')

For the domain you can use:

你可使用的域名:

var domain = window.location.hostname;

For the port you can use:

对于您可以使用的端口:

var port = window.location.port;

Keep in mind that the port will be an empty string if it is not visible in the URL. For example:

请记住,如果该端口在URL中不可见,则该端口将是一个空字符串。例如:

If you need to show 80/443 when you have no port use

如果在没有端口使用时需要显示80/443

var port = window.location.port || (protocol === 'https' ? '443' : '80');

#8


5  

Indeed, window.location.origin works fine in browsers following standards, but guess what. IE isn't following standards.

事实上,window.location。origin在遵循标准的浏览器中工作得很好,但是你猜怎么着。即不遵循的标准。

So because of that, this is what worked for me in IE, FireFox and Chrome:

正因为如此,这就是我在IE,火狐和Chrome中的应用:

var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');

but for possible future enhancements which could cause conflicts, I specified the "window" reference before the "location" object.

但是,对于将来可能导致冲突的增强,我在“location”对象之前指定了“window”引用。

var full = window.location.protocol+'//'+window.location.hostname+(window.location.port ? ':'+window.location.port: '');

#9


2  

var http = location.protocol;
var slashes = http.concat("//");
var host = slashes.concat(window.location.hostname);

#10


2  

var getBasePath = function(url) {
    var r = ('' + url).match(/^(https?:)?\/\/[^/]+/i);
    return r ? r[0] : '';
};

#11


2  

Try use a regular expression (Regex), which will be quite useful when you want to validate / extract stuff or even do some simple parsing in javascript.

尝试使用正则表达式(Regex),当您想要验证/提取内容,甚至在javascript中执行一些简单的解析时,它将非常有用。

The regex is :

正则表达式是:

/([a-zA-Z]+):\/\/([\-\w\.]+)(?:\:(\d{0,5}))?/

Demonstration:

演示:

function breakURL(url){

     matches = /([a-zA-Z]+):\/\/([\-\w\.]+)(?:\:(\d{0,5}))?/.exec(url);

     foo = new Array();

     if(matches){
          for( i = 1; i < matches.length ; i++){ foo.push(matches[i]); }
     }

     return foo
}

url = "https://www.google.co.uk:55699/search?q=http%3A%2F%2F&oq=http%3A%2F%2F&aqs=chrome..69i57j69i60l3j69i65l2.2342j0j4&sourceid=chrome&ie=UTF-8"


breakURL(url);       // [https, www.google.co.uk, 55699] 
breakURL();          // []
breakURL("asf");     // []
breakURL("asd://");  // []
breakURL("asd://a"); // [asd, a, undefined]

Now you can do validation as well.

现在您还可以进行验证。

#12


1  

David's answer is great and very comprehensive but won't work with server side javascript because of the document.createElement calls (document won't be defined).

David的回答非常全面,但是由于文档的原因,无法使用服务器端javascript。createElement调用(文档不会被定义)。

I wrote a simple component that covers arbitrary urls on the server or within a browser and parses them into an object. You can use parseUrl() as follows to get the base url and port without the path or query string:

我编写了一个简单的组件,该组件涵盖服务器或浏览器中的任意url,并将它们解析为对象。您可以使用parseUrl()来获取基本url和没有路径或查询字符串的端口:

var url = 'https://localhost:8181/ContactUs-1.0/contact?lang=it&report_type=consumer';
var urlObject = parseUrl(url);
var newUrl = urlObject.protocol + '//' + urlObject.host;

Like David's method, this also provides all of the pieces of the url within the url object.

与David的方法一样,它还提供url对象中url的所有部分。

urlObject.href         // 'https://localhost:8181/ContactUs-1.0/contact?lang=it&report_type=consumer'
urlObject.searchParams // { lang: 'it', report_type: 'consumer' }
urlObject.hash         // ''
urlObject.search       // '?lang=it&report_type=consumer'
urlObject.protocol     // 'https:'
urlObject.host         // 'localhost:8181'
urlObject.hostname     // 'localhost'
urlObject.path         // '/ContactUs-1.0/contact'

Feel free to import the component to use the parseUrl method.

请随意导入组件以使用parseUrl方法。