检测具有子域的 url 中的主机
Detect host of in a url with a subdomain
如果有一堆URL的:
sub1.sub.example.com
sub2.sub.example.com
sub3.sub.example.com
sub4.sub.example.com
等
如何检测主机名是否为 something.sub.example.com
?
我试过的方法没有用:
if (window.location.hostname == "*.sub.example.com") {
//actions
}
我相信你可以使用 String#endsWith
来做你想做的事情:
if (window.location.hostname.endswith(".sub.example.com")) { . . . }
正如 Jake Holzinger 在评论中指出的那样,IE 不支持 String#endsWith
。一个具有更好兼容性的简单正则表达式解决方案
// This is a Regular Expression literal meaning
// a string ending with ".sub.example.com" (case-insensitive)
var regexSubdomainPattern = /\.sub\.example\.com$/ig;
if (regexSubdomainPattern.test(window.location.hostname)) { . . . }
String (object) Prototype
包含一个名为 includes()
的便捷方法
因此您可以采用任何字符串参数并使用以下代码
function ddcc(what){ // ddcc - domain dot com check
return what.includes('sub.example.com');
}
var test = 'wwww.madeup.sub.example.com';
console.log(ddcc(test));
// so in practice - if ddcc(window.location.hostname) { .. } will do the trick
应该可以为您服务。
编辑: 如果您坚持 .hostname
以 sub.example.com
结尾,那么:
function ddcc(what) { // ddcc - domain dot com check
return what.includes('sub.example.com') ?
what.substring(what.indexOf('sub.example.com'), what.length) === 'sub.example.com' :
false;
}
var test = 'madeup.sub.example.com.fakelink';
console.log(ddcc(test));
如您所见,我将 .fakelink
附加到我们的 test
变量。虽然它包括 sub.example.com
但它 returns 和 false
一样。
如果有一堆URL的:
sub1.sub.example.com
sub2.sub.example.com
sub3.sub.example.com
sub4.sub.example.com
等
如何检测主机名是否为 something.sub.example.com
?
我试过的方法没有用:
if (window.location.hostname == "*.sub.example.com") {
//actions
}
我相信你可以使用 String#endsWith
来做你想做的事情:
if (window.location.hostname.endswith(".sub.example.com")) { . . . }
正如 Jake Holzinger 在评论中指出的那样,IE 不支持 String#endsWith
。一个具有更好兼容性的简单正则表达式解决方案
// This is a Regular Expression literal meaning
// a string ending with ".sub.example.com" (case-insensitive)
var regexSubdomainPattern = /\.sub\.example\.com$/ig;
if (regexSubdomainPattern.test(window.location.hostname)) { . . . }
String (object) Prototype
包含一个名为 includes()
因此您可以采用任何字符串参数并使用以下代码
function ddcc(what){ // ddcc - domain dot com check
return what.includes('sub.example.com');
}
var test = 'wwww.madeup.sub.example.com';
console.log(ddcc(test));
// so in practice - if ddcc(window.location.hostname) { .. } will do the trick
应该可以为您服务。
编辑: 如果您坚持 .hostname
以 sub.example.com
结尾,那么:
function ddcc(what) { // ddcc - domain dot com check
return what.includes('sub.example.com') ?
what.substring(what.indexOf('sub.example.com'), what.length) === 'sub.example.com' :
false;
}
var test = 'madeup.sub.example.com.fakelink';
console.log(ddcc(test));
如您所见,我将 .fakelink
附加到我们的 test
变量。虽然它包括 sub.example.com
但它 returns 和 false
一样。