Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"; document.write(str.replace("^[\w]*\/\/[\w]*$","")); 
like image 999
user549757 Avatar asked Jun 07 '11 09:06

user549757


People also ask

What is relative URL and absolute URL?

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.

How do I get a relative URL?

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.

Is absolute URL better than relative?

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.


1 Answers

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.

like image 121
lonesomeday Avatar answered Sep 19 '22 10:09

lonesomeday