How to get URL path from browser using JavaScript?

Using java script we can access the current url in our page. We have plenty of JS methods to access and we can manipulate as per our need. I this post am using some of the javascript methods to get the URL from the address bar.

Here i have shown some JS method based on this URL : http://localhost:8080/project/a1/a2?search=data#listview

  • = localhost
  • window.location.href = Returns entire URL
  • window.location.hash= #listview
  • window.location.port = 8080
  • window.location.protocol = http:
  • = ?search=data#top
  • window.location.pathname = /project/a1/a2

If you want to get each segment in the pathname we can split the string using “/”

var pathSegment = window.location.pathname.split( '/' );

the above code splits pathname based on “/” and stored it in the form of array. Example: pathSegment[0].