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

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

当前回答

尝试使用正则表达式(Regex),当你想要验证/提取东西或甚至用javascript做一些简单的解析时,它将非常有用。

正则表达式是:

/([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]

现在你也可以进行验证了。

其他回答

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

首先获取当前地址

var url = window.location.href

然后解析这个字符串

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

你的网址是:

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

实际上,window.location.origin在遵循标准的浏览器中工作得很好,但你猜怎么着。IE没有遵循标准。

正因为如此,我在IE、FireFox和Chrome浏览器中使用了这个方法:

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

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

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

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

方法1:使用URL API(注意:不支持IE11)

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

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

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

方法2(旧方法):在DOM中使用浏览器内置的解析器

如果您需要在旧的浏览器上也可以使用这个选项。

//  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');

就是这样!

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

//  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:'

附加功能:搜索参数

机会是你可能会想分开搜索url参数以及,因为'?startIndex=1&pageSize=10'本身并不太有用。

如果你使用上面的方法1 (URL API),你只需使用searchParams getter:

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

或者获取所有参数:

function searchParamsToObj(searchParams) {
  const paramsMap = Array
    .from(url.searchParams)
    .reduce((params, [key, val]) => params.set(key, val), new Map());
  return Object.fromEntries(paramsMap);
}
searchParamsToObj(url.searchParams);
// -> { startIndex: '1', pageSize: '10' }

如果你使用方法2(旧的方式),你可以使用这样的东西:

// Simple object output (note: does NOT preserve duplicate keys).
var params = 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' }

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
}