I’m creating an eshop on one eCommerce platform (Shoptet) a I’m trying to hide few elements only on homepage but I still want to see them on subpages. These elements have same classes.
My script looks like this:
<script>
var home = "^https://644859.myshoptet.com$"
if (window.location.href.match(home)) {
$('.detail-parameters').hide();
$('.availability-value').hide();
$('.add-to-cart').hide();
}
</script>
It’s not working but when I put negation into condition (!window.location.href.match(home))
it works beautifully for subpages.
Any advices how to make it work only on homepage? The URL is real URL of eshop.
Thank you!
2
Answers
"^https://644859.myshoptet.com$"
is just a string, if you need tomatch
with a regular expression, surround it with a slash and scape the special characters with backslash.Keep in mind that
window.location.href
could end with slash at the end likehttps://644859.myshoptet.com/
as @CBroe mentionedSo the safer check is using
startsWith
method or just remove the dollar sign at the end of your regular expression.you are hardcoding that pathname but here you are trying to math the pathname for the home , and it could change from https or http or wherever it is , so you should use regular expressions and avoid hardcoding the pathname
so you new code would be like this .
let me also break down to you this regular expression
the ^ and the $ are to make sure that the pathname match the start and end of the URL, ensuring an exact match.
/? matches an optional trailing slash after the domain , so you should be careful using it , you should remove if you only the exact path ‘/’
you will remove it in case you dont want to have the optional trailing in the pathname .
using this approach allows you to use regular expressions to match the homepage URL more flexibly