29 javascript url greasemonkey
我有URL http://somesubdomain.domain.com(子域名可能会有所不同,域名始终相同).需要使用子域名并使用greasemonkey(例如使用URL domain.com/some/path/here/somesubdomain打开一个新窗口,使用domain.com/some/path/here/somesubdomain)重新加载页面.
Der*_*ley 49
var full = window.location.host
//window.location.host is subdomain.domain.com
var parts = full.split('.')
var sub = parts[0]
var domain = parts[1]
var type = parts[2]
//sub is 'subdomain', 'domain', type is 'com'
var newUrl = 'http://' + domain + '.' + type + '/your/other/path/' + subDomain
window.open(newUrl);
Run Code Online (Sandbox Code Playgroud)
Vla*_*lip 18
Derek提供的答案适用于最常见的情况,但不适用于"xxx.xxx"子域或"host.co.uk".(另外,使用window.location.host,还将检索未被处理的端口号:http://www.w3schools.com/jsref/prop_loc_host.asp)
说实话,我没有看到这个问题的完美解决方案.就个人而言,我已经创建了一个主机名拆分方法,我经常使用它,因为它涵盖了大量的主机名.
此方法将主机名拆分为 {domain: "", type: "", subdomain: ""}
function splitHostname() {
var result = {};
var regexParse = new RegExp('([a-z\-0-9]{2,63})\.([a-z\.]{2,5})$');
var urlParts = regexParse.exec(window.location.hostname);
result.domain = urlParts[1];
result.type = urlParts[2];
result.subdomain = window.location.hostname.replace(result.domain + '.' + result.type, '').slice(0, -1);;
return result;
}
console.log(splitHostname());
Run Code Online (Sandbox Code Playgroud)
此方法仅将子域作为字符串返回:
function getSubdomain(hostname) {
var regexParse = new RegExp('[a-z\-0-9]{2,63}\.[a-z\.]{2,5}$');
var urlParts = regexParse.exec(hostname);
return hostname.replace(urlParts[0],'').slice(0, -1);
}
console.log(getSubdomain(window.location.hostname));
// for use in node with express: getSubdomain(req.hostname)
Run Code Online (Sandbox Code Playgroud)
这两种方法适用于大多数常见域(包括co.uk)
注意:slice子域末尾是删除额外的点.
我希望这能解决你的问题.