从URL获取协议,域和端口

时间:2011-08-04 12:38:14

标签: javascript url dns protocols port

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

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

18 个答案:

答案 0 :(得分:519)

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

答案 1 :(得分:157)

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

方法1:使用URL API(警告:不支持IE11)

您可以使用URL API(IE11不支持,但可以使用everywhere else)。

这样也可以轻松访问search params。另一个好处是:它可以在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:'

奖励:搜索参数

您可能也想要拆分搜索网址参数,因为'?startIndex = 1& pageSize = 10'它本身并不常用。

如果您使用上面的方法1(URL API),则只需使用searchParams getters:

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

或者获取所有参数:

Array
    .from(url.searchParams)
    .reduce((accum, [key, val]) => {
        accum[key] = val;
        return accum;
    }, {});
// -> { 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' }

答案 2 :(得分:131)

首先获取当前地址

var url = window.location.href

然后只解析该字符串

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

你的网址是:

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

希望这有帮助

答案 3 :(得分:115)

出于某种原因,所有答案都是过度杀伤力。这就是所需要的:

window.location.origin

可在此处找到更多详细信息:https://developer.mozilla.org/en-US/docs/Web/API/window.location#Properties

答案 4 :(得分:50)

正如已经提到的那样,尚未完全支持window.location.origin但是不是使用它或创建新变量来使用,我更喜欢检查它以及它是否未设置为设置它

例如;

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

几个月前我实际上写了这篇文章A fix for window.location.origin

答案 5 :(得分:29)

<强>宿主

var url = window.location.host;

返回localhost:2679

<强>主机名

var url = window.location.hostname;

返回localhost

答案 6 :(得分:13)

  

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

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

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

对于您可以使用的域名:

var domain = window.location.hostname;

您可以使用以下端口:

var port = window.location.port;

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

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

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

答案 7 :(得分:11)

window.location.origin就足够了。

答案 8 :(得分:6)

确实, 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: '');

答案 9 :(得分:2)

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

答案 10 :(得分:2)

为什么不使用:

let full = window.location.origin

答案 11 :(得分:2)

尝试使用正则表达式(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]

现在你也可以进行验证。

答案 12 :(得分:2)

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

答案 13 :(得分:0)

带有可配置参数的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
}

答案 14 :(得分:0)

window.location.protocol +'//'+ window.location.host

答案 15 :(得分:0)

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

@section Scripts
{
@await Html.PartialAsync("_ValidationScriptsPartial")
<script type="text/javascript">

    function showSharingView(title) {
        var url = "@Url.Action("ShowShareDialog", "Home")" + "?workbookTitle=" + encodeURI(title);
        $('#shareFormContainer').load(url,
            function() {
                $('#shareFormModal').modal("show");
                $.validator.unobtrusive.parse("#partialform");
            });
    }
    function hideSharingView() {
        $('#shareFormModal').modal("hide");
    }
</script>
}

答案 16 :(得分:0)

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

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

答案 17 :(得分:0)

使用ES6 template literals

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

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

相关问题