How to split url to get url path in JavaScript

Why don't you use the split function and work from there. The split function will break your URL out fully and from there you just need to look for the second last and last items.

Here is an example:

var initial_url = 'http://www.mymainsite.com/path/path/needthispath/somepath';
var url = initial_url .split( '/' );

var updated_url= document.location.hostname + '/' + url[ url.length - 2 ] + '/' + url[ url.length - 1 ];

First solution (URL object)

The URL object can be used for parsing, constructing, normalizing, encoding URLs, and so on.

var url = 'http://www.mymainsite.com/somepath/path2/path3/path4';

var pathname = new URL(url).pathname;

console.log(pathname);

The URL interface represents an object providing static methods used for creating object URLs.

  • See the documentation for URL interface on Mozilla MDN

  • The Browser support is pretty good in 2017 (~ 90% but not IE11 nor below)


Second solution (a kind of a hack)

var urlHack = document.createElement('a');
urlHack.href = 'http://www.mymainsite.com/somepath/path2/path3/path4';

console.log(urlHack.pathname);

// you can even call this object with these properties:
// protocol, host, hostname, port, pathname, hash, search, origin

You can use the URL API, though support is variable.

Alternatively, you could use URI.js.

Both allow you to get different parts of an URL, as well as build new URLs from parts.

Tags:

Javascript