skip to Main Content

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


  1. "^https://644859.myshoptet.com$" is just a string, if you need to match with a regular expression, surround it with a slash and scape the special characters with backslash.

    var home = /^https://644859.myshoptet.com$/
    if (window.location.href.match(home)) {
        $('.detail-parameters').hide();
        $('.availability-value').hide();
        $('.add-to-cart').hide();
    }
    

    Keep in mind that window.location.href could end with slash at the end like https://644859.myshoptet.com/ as @CBroe mentioned

    So the safer check is using startsWith method or just remove the dollar sign at the end of your regular expression.

    var home = /^https://644859.myshoptet.com/
    if (window.location.href.match(home)) {
      // ...code
    }
    
    var home = "https:644859.myshoptet.com"
    if (window.location.href.startsWith(home)) {
      // ...code
    }
    
    Login or Signup to reply.
  2. 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 .

    <script>
    var homeRegex = /^https://644859.myshoptet.com/?$/; // Regular expression to match the homepage URL
    
    if (homeRegex.test(window.location.href)) {
        $('.detail-parameters').hide();
        $('.availability-value').hide();
        $('.add-to-cart').hide();
    }
    </script>
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search