How to check by the url if the page is the index

Asked

Viewed 141 times

0

As I get through JS, if my url is the index?

I have a code like this:

window.onload = function () {
    url = window.location.href;

    if (url.match("/dashboard")) {
        [...]
    }
}

that checks if it is in the Dashboard url. But how do I check if it is in the index? Since there is no /index in the url, it is simply https://localhost:8080?

I can’t do it like this:

if (url == "https://localhost:8080/") {
    [...]
}

Because in the future this url will certainly be another one, and I will need to change the code (which I don’t want).

  • What is the value of url when you access the index?

  • @Andersoncarloswoss the value is https://localhost:8080/

1 answer

3

Instead of href, you can use pathname, which is the part of the URL you want to check:

const url = window.location;

console.log(url.pathname);

In this case, in the index the value of url.pathname will be "/".

  • and in the case of a path ?? For example, if the url is https://localhost:8080/dash/board/1/js? the value will be /js?

  • @edro No, will be the respective value to the path of the URL. See What is a URL?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.