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:
va
don't forget that \
is an escape character in strings, so if you would like to write regex in strings, ensure you type \
twice for every \
you need. Example: /\w/
→ "\\w"
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.