简体   繁体   中英

How to split url to get url path in 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?

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.


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

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.

Can you please help me with this split? I tried to do it but it doesn't work.

A:\Apis-Utiles\Api-PDFs\src\pdf\111111111.pdf

 function url($url) { var url = $url.split( '//' ); if (url[0] === "http:" || url[0] === "https:") { var protocol = url[0] + "//"; var host = url[1].split( '/' )[0]; url = protocol + host; var path = $url.split(url)[1]; return { protocol: protocol, host: host, path: path }; } } var $url = url("http://www.mymainsite.com/path/path/needthispath/somepath"); console.log($url.protocol); // http:// console.log($url.host); // www.mymainsite.com console.log($url.path); // /path/path/needthispath/somepath

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM