If you are kooking for a site's URL information, then the window.location
object is for you! Use its properties to get information on the current page address or use its methods to do some page redirect or refresh.
Notice: window.location only works in browser site rendering
For the following URL:
https://fizzy.cc:8080/example/index.html?s=javascript#2
So to get the full URL path in JavaScript:
Pathname Break-up
If you need to break up the pathname, for example, a URL like https://fizzy.cc/blah/blah/blah/index.html
, you can split the string on “/” characters:
Then access the different parts by the parts of the array, like:
To put that pathname back together, you can stitch together the array and put the “/”s back in:
How to change URL properties
Not only can you call these location properties to retrieve the URL information. You can use it to set new properties and change the URL.
Here's the complete list of properties that you can change:
window.location Methods
window.location | Description |
---|---|
.assign() |
Navigates to the given URL |
.replace() |
Navigates to given URL & removes current page from the session history |
.reload() |
Reload the current page |
.toString() |
Returns the URL |