user549757 user549757 - 1 year ago 147
Javascript Question

Get relative URL from absolute URL

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download