So I have this code that adds a class to my section
whenever there’s a url slug detected or contains that url.
<script type="text/javascript">
jQuery(document).ready(function() {
if (window.location.href.indexOf('product') > -1 || window.location.href.indexOf('about') > -1 || window.location.href.indexOf('careers') > -1 || window.location.href.indexOf('pricing') > -1) {
$('#main-navigation-sec').addClass('product-nav-sec');
}
});
</script>
But this one might be too long to be inserted on the if
condition for all. I’m trying out certain codes to make it into an array and can’t seem to properly execute the right way. Any chance how to properly simplify it? It would be a great help. I’m referencing this array of indexOf
here
3
Answers
Working on the assumption you want something to determine if the
href
contains one of a set of possible strings:You could modify
containsAny
so it returned the positions of the matched elements instead of a boolean easily.Here is a shortened version of your code using a single regex:
Notice that this tests for a
/
followed by a keyword that is standalone, indicated by the word boundaryb
. It’s good to be specific in order to avoid false positives, such ashttps://example.com/foo/bar?utm=whereabouts