JavaScript - Get Portion of Url Path

JavaScript - Get Portion of URL Path

There is a property of the built-in window.location object that will provide that for the current window.

// If URL is http://www.somedomain.com/account/search?filter=a#top

window.location.pathname // /account/search

// For reference:

window.location.host // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash // #top
window.location.href // http://www.somedomain.com/account/search?filter=a#top
window.location.port // (empty string)
window.location.protocol // http:
window.location.search // ?filter=a

Update, use the same properties for any URL:

It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing window.location object and anchor elements implement the interface.

So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:

var el = document.createElement('a');
el.href = "http://www.somedomain.com/account/search?filter=a#top";

el.host // www.somedomain.com (includes port if there is one[1])
el.hostname // www.somedomain.com
el.hash // #top
el.href // http://www.somedomain.com/account/search?filter=a#top
el.pathname // /account/search
el.port // (port if there is one[1])
el.protocol // http:
el.search // ?filter=a

[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right

This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.

JSFiddle example

There's also a coming URL object that will offer this support for URLs themselves, without the anchor element. Looks like no stable browsers support it at this time, but it is said to be coming in Firefox 26. When you think you might have support for it, try it out here.

How do I parse a URL into hostname and path in javascript?

var getLocation = function(href) {
var l = document.createElement("a");
l.href = href;
return l;
};
var l = getLocation("http://example.com/path");
console.debug(l.hostname)
>> "example.com"
console.debug(l.pathname)
>> "/path"

Get the first part of a url path

var first = $(location).attr('pathname');

first.indexOf(1);

first.toLowerCase();

first = first.split("/")[1];

alert(first);

Javascript to grab parts of the URL

As users in the comments mentioned, the url string is no different than any other string. You can easily just use the string split method to return an array of strings between the / character

To get the href location you can use window.location.href or location.href

var url_str = window.location.href;

The str.split() function takes a separator parameter in this case '/' and returns an array of strings that were found. For example it would return this given your example url http://www.domain.com/part1/part2/part3/part4:

var arr = url_str.split('/');

["http:", "", "www.domain.com", "part1", "part2", "part3", "part4"]

The array .slice(begin,end) method returns a portion of the array from the begin to end(default end of the array) parameters (both zero based, first element = 0, 10th = 9).

To get the last 4 parts of our example array we do the following:

var values = arr.slice(3);

["part1", "part2", "part3", "part4"]

Now you can either access the array directly to get each value or assign them to variables:

console.log("Your first folder is "+values[0]); //direct access

or

var var1 = values[0];
var var2 = values[1];
var var3 = values[2];
var var4 = values[3];

console.log("Your first folder is " + var1]); //variable alias

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);

Get Only a Part of the Url with Javascript

You can try this brother. Thank you.

let path = window.location.pathname;

path = path.split('/').filter((el, index) => index !== 0).join('/');

console.log(path);

Get portion of URL path and store value in string

you can use the decodeURI function for that, no need to replace the %20s with " ", just parse in the url as is and it will remove all special characters.

const url = "/data/Sarah's%20Day%20Salon";
const decodedString = decodeURI(url);
const stringArray = decodedString.split('/');
const storeName = stringArray[stringArray.length - 1]
console.log(storeName);

Last segment of URL with JavaScript

You can also use the lastIndexOf() function to locate the last occurrence of the / character in your URL, then the substring() function to return the substring starting from that location:

console.log(this.href.substring(this.href.lastIndexOf('/') + 1));

That way, you'll avoid creating an array containing all your URL segments, as split() does.

Way to extract a portion of a path from a URL using JavaScript?

You could go about doing it like this,

const url=new URL('http://www.somedomain.com/account/6099bb4e2eb24bab85e8b76851a14260/search?filter=a#top');

/*
url.pathname="/account/6099bb4e2eb24bab85e8b76851a14260/search"
url.pathname.split('/')=["","account","6099bb4e2eb24bab85e8b76851a14260","search"]
*/
const accountId=url.pathname.split('/')[2];
console.log(accountId);

Refer this for more on how to use the URL object in JS,
https://developer.mozilla.org/en-US/docs/Web/API/URL

How can you see how many paths a URL has?

So we can approach this question by first thinking about what a path is. Fundamentally, a path is a way to access a resource, and you usually get there via folders. We can get the pathname of a location by using

window.location.pathname

in the case of our current url, it will return

/questions/62353998/how-can-you-see-how-many-paths-a-url-has

or

/questions/62353998/how-can-you-see-how-many-paths-a-url-has/

So, we can get the exact answer by trimming off "/" paths (which are empty) and counting them up. Using javascript, we can get this number by doing

window.location.pathname.split("/").filter(a => a.length > 0).length

Breaking it down, we're

  1. getting the pathname (window.location.pathname)

  2. splitting the path into the directories we've traveled to get there (.split("/"))

  3. filtering out empty paths "" (.filter(a => a.length > 0))

generally of course, you can also do some complex regex

window.location.href.split(/[?#]/).shift().match(/\/[^/]+?/g).length

(last code snippet lifted from https://stackoverflow.com/a/36983925/4166655)



Related Topics



Leave a reply



Submit