How to split url to get url path in JavaScript

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)