How to hide code / Div based on contents in URL using Javascript

There are some reasons where you want certain button / image to be hidden for some section of URL’s. For example, we are showing “Publish New Ad” button on one of our website which is visible for all URL’s of a website, and same also becomes visible on “publish-new.html” html page which is opened once user clicks on that button.

But since the user is already on “publish-new.html” page, there is no point in showing the same button again to user, so we wanted to hide this button only on URL which contains string “publish-new”. We achieved this with following Javascript code,


<script>
URL = window.location.href;
if (!URL.includes("publish-new")) {
button_html = "<a href=\"https://www.greenecosystem.in/fconn/publish-new.html\" style=\"position:fixed;bottom:10px; left: 35%; right: 35%; width: 30%;\"> <button type=\"button\" class=\"btn btn-primary btn-sm\" style=\"background-color:#2f9d17;\"> <b> Post Free Ad </b></button></a>";
}
document.getElementById("hide_publish_button").innerHTML = button_html;
</script>
<p id="hide_publish_button"></p>

As you can see above, we used “window.location.href” to know what is the current URL and then with “!URL.includes(“publish-new”)” code, we decided to show buttons only when the URL doesn’t included “publish-new” and hence “Publish New” button will gets hidden for “publish-new.html”