我试图寻找一个相对简单和可靠的方法来提取一个字符串变量使用JavaScript(或jQuery的)的基本URL。
例如,假设是这样的:
http://www.sitename.com/article/2009/09/14/this-is-an-article/
我想获得:
http://www.sitename.com/
是正则表达式的最佳选择? 如果是这样,有什么语句可以我使用分配给定字符串提取到一个新的变量的基本URL?
我已经做了这方面的一些搜索,但一切我在JavaScript世界发现似乎围绕着收集使用location.host或类似的实际文档的URL此信息。
编辑:一些人抱怨,它并没有考虑到协议。 所以,我决定升级的代码,因为它被标记为答案。 对于那些谁喜欢1行的代码......好后悔这究竟是为什么我们使用代码极小,代码应该是人类可读的,这种方式在我看来,更好的... ...。
var pathArray = "https://somedomain.com".split( '/' );
var protocol = pathArray[0];
var host = pathArray[2];
var url = protocol + '//' + host;
或者使用大卫的解决方案从下面。
基于WebKit的浏览器,Firefox浏览器的版本21和Internet Explorer的最新版本(IE 10和11)实施location.origin
。
location.origin
包括协议 ,所述结构域和任选的URL的端口 。
例如, location.origin
URL的http://www.sitename.com/article/2009/09/14/this-is-an-article/
是http://www.sitename.com
。
要定位的浏览器不支持location.origin
使用下面的简洁填充工具:
if (typeof location.origin === 'undefined')
location.origin = location.protocol + '//' + location.host;
没有理由做劈叉从字符串是一个链接获取路径,主机名等。 你只需要使用一个链接
//create a new element link with your link
var a = document.createElement("a");
a.href="http://www.sitename.com/article/2009/09/14/this-is-an-article/";
//hide it from view when it is added
a.style.display="none";
//add it
document.body.appendChild(a);
//read the links "features"
alert(a.protocol);
alert(a.hostname)
alert(a.pathname)
alert(a.port);
alert(a.hash);
//remove it
document.body.removeChild(a);
您可以轻松地使用jQuery追加元素并读取其ATTR做到这一点。
var host = location.protocol + '//' + location.host + '/';
String.prototype.url = function() {
const a = $('<a />').attr('href', this)[0];
// or if you are not using jQuery