从URL中获取协议、域名和端口

405

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

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

8

这是我正在使用的解决方案:

const result = `${ window.location.protocol }//${ window.location.host }`;

编辑:

为了实现跨浏览器兼容性,请使用以下内容:

const result = `${ window.location.protocol }//${ window.location.hostname + (window.location.port ? ':' + window.location.port: '') }`;

1
已点赞,但window.location.host可能不是最佳跨浏览器选择。 - nathanfranke
1
谢谢,我已经在我的原始答案中添加了跨浏览器兼容性。 - JulienRioux

4

使用ES6 模板字面量

const url = `${location.protocol}//${location.hostname}${location.port?':'+location.port:''}`;

document.getElementById("result").innerText = url;
<div id="result"></div>

您可以简化为:

const url = `${location.protocol}//${location.host}`;

document.getElementById("result").innerText = url;
<div id="result"></div>


3

如果你想在JavaScript中验证/提取内容或进行简单的解析,尝试使用正则表达式(Regex),这将非常有用。

正则表达式是:

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

演示:

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]

现在您也可以进行验证。

一个有效的RFC 3986 URL方案必须由“字母开头,后面跟着任意组合的字母、数字、加号(+)、句点(.)或连字号(-)”组成。--https://dev59.com/XWox5IYBdhLWcg3wi0zF#9142331(这是用于Python中URI / IRI的“urn:ietf:rfc:3897(URI)/ urn:ietf:rfc:3897(IRI)”方案的正则表达式:https://github.com/dgerber/rfc3987/blob/master/rfc3987.py#L147) - Wes Turner

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

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

2
请考虑解释您的答案。不要假设问题提出者能够理解代码中不同部分的重要性。 - ADyson

2

适用于所有浏览器的简单答案:

最初的回答。
let origin;

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

origin = window.location.origin;

1

使用可配置参数的ES6风格。

/**
 * Get the current URL from `window` context object.
 * Will return the fully qualified URL if neccessary:
 *   getCurrentBaseURL(true, false) // `http://localhost/` - `https://localhost:3000/`
 *   getCurrentBaseURL(true, true) // `http://www.example.com` - `https://www.example.com:8080`
 *   getCurrentBaseURL(false, true) // `www.example.com` - `localhost:3000`
 *
 * @param {boolean} [includeProtocol=true]
 * @param {boolean} [removeTrailingSlash=false]
 * @returns {string} The current base URL.
 */
export const getCurrentBaseURL = (includeProtocol = true, removeTrailingSlash = false) => {
  if (!window || !window.location || !window.location.hostname || !window.location.protocol) {
    console.error(
      `The getCurrentBaseURL function must be called from a context in which window object exists. Yet, window is ${window}`,
      [window, window.location, window.location.hostname, window.location.protocol],
    )
    throw new TypeError('Whole or part of window is not defined.')
  }

  const URL = `${includeProtocol ? `${window.location.protocol}//` : ''}${window.location.hostname}${
    window.location.port ? `:${window.location.port}` : ''
  }${removeTrailingSlash ? '' : '/'}`

  // console.log(`The URL is ${URL}`)

  return URL
}

1

窗口位置协议 + '//' + 窗口位置主机


-1
console.log(`${req.protocol}://${req.get('host')}/${req.originalUrl}`);
  • req.protocol - 返回所使用的协议(例如 HTTP
  • req.get(host) - 返回带有端口号的主机名(例如 localhost:8080

但是什么是req呢?这个问题没有Express框架标签,例如你可能需要通过CLI解析URL来进行应用程序。 - e-info128

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接