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?
var newURL="http://www.example.com/index.html/homePage/aboutus/"; console. log(newURL); var splitURL=newURL. toString(). split("/"); console.
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.
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)
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
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 ];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With