How to get request uri from location.href in javascript?

What I get from location.href is like this:

But I only want to get questions/ask (no / at the first character)

How to achieve this?

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

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);

You can use location.pathname.substring(1)

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)

If you need the query params you can use:

var path = (;

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

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

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Why is Javascript's Math.floor the slowest way to calculate floor in Javascript?

Similar Posts