Skip to content Skip to sidebar Skip to footer

How To Get Request Uri From Location.href In Javascript?

What I get from location.href is like this: http://stackoverflow.com/questions/ask But I only want to get questions/ask (no / at the first character) How to achieve this?

Solution 1:

location.pathname.substr(1) would that be.

Solution 2:

The location object has a pathname property.

This will give you /questions/ask and to remove the first character, use substring(1):

var path = location.pathname.substring(1);

Solution 3:

You can use location.pathname.substring(1)

Solution 4:

var uri = window.location.href.substr(window.location.protocol.length + window.location.hostname.length + 2);

This code also includes GET and HASHTAGS (basically everything after hostname)

Solution 5:

If you need the query params you can use:

var path = (window.location.pathname+window.location.search).substr(1);

If you need access to the hash as well you can use:

var path = (window.location.href.replace(window.location.origin, '')).substr(1);

Post a Comment for "How To Get Request Uri From Location.href In Javascript?"