How to implement wildcards for window.location.pathname [duplicate]
How to implement wildcards for window.location.pathname [duplicate]
This question already has an answer here:
I have the following code and I would like to make the function work on any URL containing "blog" instead of a specific URL. Please help me with the correct syntax, thanks.
window.setTimeout(function() {
if (window.location.pathname != '/home/legal-documentation' &&
window.location.pathname != '/home/blog/australian-business-news'
) {
erOpenLoginRegisterbox(jQuery);
}
return false;
}, 1000);
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
2 Answers
2
I think you are looking for 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), and then compare it to 'BLOG'
indexOf
window.setTimeout(function() {
if (window.location.pathname.toUpperCase().indexOf('BLOG') === -1) {
erOpenLoginRegisterbox(jQuery);
}
return false;
}, 1000);
What you are looking for is a Regular Expression. These are used to match a certain combination of characters, in your case, you can use String.prototype.match() in order to find Strings containing the word "blog" using this RegEx:
String.prototype.match()
/blog/gi
or, in your function:
window.setTimeout(function() {
if (window.location.pathname.match(/blog/gi)) {
erOpenLoginRegisterbox(jQuery);
}
return false;
}, 1000);
Obligatory xkcd link.
– Heretic Monkey
Jul 1 at 21:17
There's at some point going to be a XKCD Comic for every situation
– Luca
Jul 1 at 21:19
Feedback: rightly or wrongly, the wording of your questions matters on Stack Overflow. "Please help me with the correct syntax" strikes me as an unresearched request for free work. If you want to get the best out of this platform, show what you have tried, and what specific problem you had with it.
– halfer
Jul 1 at 21:09