Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split url to get url path in JavaScript

Tags:

javascript

I have constructed a url path that are pointing to different hostname www.mysite.com, so for example:

var myMainSite = 'www.mymainsite.com' + '/somepath';

so this is equivalent to www.mymainsite.com/path/path/needthispath/somepath.

How I'm doing it now is like the code below and this gives me a bunch of indexes of the url in the console.log.

var splitUrl = myMainSite.split('/');

console.log looks like:

0: http://
1: www.
2: mysite.com
3: path
4: path
5: needthispath
6: somepath

and I concat them like splitUrl[5]+'/'+splitUrl[6] and it doesn't look pretty at all.

So my question is how to split/remove url location http://www.mymainsite.com/ to get the url path needthispath/somepath in js? Is there a quicker and cleaner way of doing this?

like image 265
nCore Avatar asked Sep 05 '16 16:09

nCore


People also ask

How do you split a URL?

var newURL="http://www.example.com/index.html/homePage/aboutus/"; console. log(newURL); var splitURL=newURL. toString(). split("/"); console.

How do I get the URL of a website using JavaScript?

You can simply call the window. location. href property which will return you the complete URL of the webpage including hostname, pathname, and query string.


3 Answers

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
like image 122
Inanc Gumus Avatar answered Oct 18 '22 03:10

Inanc Gumus


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 ];
like image 21
The Gav Lad Avatar answered Oct 18 '22 03:10

The Gav Lad


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.

like image 3
jcaron Avatar answered Oct 18 '22 01:10

jcaron