如何为 window.location.pathname 实现通配符
How to implement wildcards for window.location.pathname
我有以下代码,我想让该函数在任何包含 "blog" 而不是特定 URL 的 URL 上运行。请帮助我正确的语法,谢谢。
window.setTimeout(function() {
if (window.location.pathname != '/home/legal-documentation' &&
window.location.pathname != '/home/blog/australian-business-news'
) {
erOpenLoginRegisterbox(jQuery);
}
return false;
}, 1000);
您要找的是 Regular Expression。这些用于匹配特定的字符组合,在您的情况下,您可以使用 String.prototype.match()
以便使用此 RegEx 查找包含单词 "blog" 的字符串:
/blog/gi
或者,在您的函数中:
window.setTimeout(function() {
if (window.location.pathname.match(/blog/gi)) {
erOpenLoginRegisterbox(jQuery);
}
return false;
}, 1000);
我认为你正在寻找 indexOf
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf It will return -1 if it does not find the string it is passed, so testing for -1 seems to correlate with your approach. Furthermore, to be on the safe side, in case you also want to exclude blog in a case-insensitive manner (in other words, you want to test for Blog, blog, BLOG, etc.), I refer to pathname as though it were uppercase (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase),然后将其与 'BLOG'
进行比较
window.setTimeout(function() {
if (window.location.pathname.toUpperCase().indexOf('BLOG') === -1) {
erOpenLoginRegisterbox(jQuery);
}
return false;
}, 1000);
我有以下代码,我想让该函数在任何包含 "blog" 而不是特定 URL 的 URL 上运行。请帮助我正确的语法,谢谢。
window.setTimeout(function() {
if (window.location.pathname != '/home/legal-documentation' &&
window.location.pathname != '/home/blog/australian-business-news'
) {
erOpenLoginRegisterbox(jQuery);
}
return false;
}, 1000);
您要找的是 Regular Expression。这些用于匹配特定的字符组合,在您的情况下,您可以使用 String.prototype.match()
以便使用此 RegEx 查找包含单词 "blog" 的字符串:
/blog/gi
或者,在您的函数中:
window.setTimeout(function() {
if (window.location.pathname.match(/blog/gi)) {
erOpenLoginRegisterbox(jQuery);
}
return false;
}, 1000);
我认为你正在寻找 indexOf
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf It will return -1 if it does not find the string it is passed, so testing for -1 seems to correlate with your approach. Furthermore, to be on the safe side, in case you also want to exclude blog in a case-insensitive manner (in other words, you want to test for Blog, blog, BLOG, etc.), I refer to pathname as though it were uppercase (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase),然后将其与 'BLOG'
window.setTimeout(function() {
if (window.location.pathname.toUpperCase().indexOf('BLOG') === -1) {
erOpenLoginRegisterbox(jQuery);
}
return false;
}, 1000);