给定一个URL作为字符串,如何只提取域和扩展名

Given a URL as a string, how to extract just the domain and extension?

本文关键字:提取 扩展名 字符串 URL 一个      更新时间:2023-09-26

给定一个包含以下格式URL的字符串:

https://www.cnn.com/
http://www.cnn.com/
http://www.cnn.com/2012/02/16/world/american-nicaragua-prison/index.html
http://edition.cnn.com/?hpt=ed_Intl

WJS/jQuery,我如何从字符串中提取所有它们的cnn.com?顶级域加扩展?

感谢

​var loc = document.createElement('a');
loc.href = 'http://www.cnn.com/2012/02/16/world/index.html';
​window.alert(loc.hostname);​ // alerts "cnn.com"

上一种方法的学分:

在javascript 中创建新的Location对象

function domain(input){
    var matches,
        output = "",
        urls = /'w+:'/'/(['w|'.]+)/;
    matches = urls.exec(input);
    if(matches !== null){
        output = matches[1];
    }
    return output;
}

考虑到有带点的顶级域,例如"co.uk",除非包含所有带点的TLD的列表,否则无法通过程序实现这一点。

var domain = location.host.split('.').slice(-2);

如果你想重新组装:

var domain = location.host.split('.').slice(-2).join('.');

但这对co.uk或其他网站不起作用。对此没有硬性规定,甚至regex也无法确定。

// something.domain.com -> domain.com
function getDomain() {
  return window.location.hostname.replace(/([a-z]+.)/,"");
}