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]*$",""));
An absolute URL contains all the information necessary to locate a resource. A relative URL locates a resource using an absolute URL as a starting point. In effect, the "complete URL" of the target is specified by concatenating the absolute and relative URLs.
To link pages using relative URL in HTML, use the <a> tag with href attribute. Relative URL is used to add a link to a page on the website. For example, /contact, /about_team, etc.
An absolute URL contains more information than a relative URL does. Relative URLs are more convenient because they are shorter and often more portable. However, you can use them only to reference links on the same server as the page that contains them.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With