Get relative URL from absolute URL
Solution 1
If by "relative URL" you mean the part of the string after the first single /
, then it's simple:
document.write(str.replace(/^(?:\/\/|[^/]+)*\//, ''));
This matches all the characters up to the first single /
in the string and replaces them with the empty string.
In: http://localhost/my/page.jsp
--> Out: /my/page.jsp
Solution 2
A nice way to do this is to use the browser's native link-parsing capabilities, using an a
element:
function getUrlParts(url) {
var a = document.createElement('a');
a.href = url;
return {
href: a.href,
host: a.host,
hostname: a.hostname,
port: a.port,
pathname: a.pathname,
protocol: a.protocol,
hash: a.hash,
search: a.search
};
}
You can then access the pathname with getUrlParts(yourUrl).pathname
.
The properties are the same as for the location
object.
Solution 3
Below snippet returns the absolute URL of the page.
var myURL = window.location.protocol + "//" + window.location.host + window.location.pathname;
If you need only the relative url just use below snippet
var myURL=window.location.pathname;
Checkout get relative URL using Javascript for more details and multiple ways to achieve the same functionality.
Solution 4
const url = new URL('https://www.example.com/path/#anchor?query=value');
const rel = url.toString().substring(url.origin.length)
console.log(rel)
// Output: /path/#anchor?query=value
Solution 5
Don't use low-level stuff like regexp etc. These things have been solved by so many other people. Especially the edge cases.
Have a look at URI.js, it should do the job: http://medialize.github.io/URI.js/docs.html#relativeto
var uri = new URI("/relative/path");
// make path relative
var relUri = uri.relativeTo("/relative/sub/foo/sub/file"); // returns a new URI instance
// relUri == "../../../path"
user549757
Updated on August 27, 2021Comments
-
user549757 over 2 years
I want to get the relative URL from an absolute URL in JavaScript using regex and the replace method.
I tried the following but it is not working:
var str="http://localhost/mypage.jsp"; document.write(str.replace("^[\w]*\/\/[\w]*$",""));
-
user549757 almost 13 years@Tim - it is not working as the way you said. Outs me the entire url :(
-
Tim Pietzcker almost 13 yearsHm, strange. Try
str.replace(/^(?:\/\/|[^\/]+)*\//, "");
, how about now? -
user549757 almost 13 years@Tim - yeah, this works now. but a little more problem. I want the part after second single
/
, can you plz help me modifying this regex? -
user549757 almost 13 years@Tim - hey Thanks Tim +1, I got it working using
str.replace(/[\w]*:\/\/[\w]*\/[\w]*/,"")
, but still waiting for solution the way you approached. :) -
Tim Pietzcker almost 13 yearsIn your example (up in your question) there is only one single slash - what should happen then?
-
user549757 almost 13 years@Tim - ya, I accept your answer as per my question. But it didnt satisfy my actual requirement, so was waiting for your response on my comment, as I find your approach more promising. Would be thankful to you if you can plz let me know how can i accomplish to get part after second single
/
-
Tim Pietzcker almost 13 yearsFor everything after the second single slash, use
/^(?:\/\/|[^\/]+)*\/[^\/]+\//
. -
Bohdan Lyzanets over 10 yearsPathname will not return
query
(a.search
) andhash
. So better variant, as for me, isvar urlParts = getUrlParts(yourUrl); var absoluteUrl = urlParts.pathname + urlParts.search + urlParts.hash
. -
MalcolmOcean almost 8 years
location.pathname
is the obvious winner for getting the active url in relative form! But why not just uselocation.href
for the absolute url? -
thedayturns over 6 yearshow is this so far down when
window.location.pathname
is obviously the correct answer here??? -
jimrandomh over 4 yearsThis answer is incorrect; if the URL has a query or a hash, they will be omitted when they shouldn't.
-
Jake over 3 yearsThis worked perfectly for me and looks like the simplest answer.
-
Raine Revere over 2 yearsNote that you have to include the code in the Gist, and it modifies
URL.prototype
.