'Get foldername from url with javascript

I want to get folder name from a URL. For example:

http://example.com/foldername/test.html

I can get the pathname like /foldername/test.html with window.location.pathname and then I just need get "foldername".

How can I get "foldername" form current URL with JavaScript? Please let me know. Thanks:)



Solution 1:[1]

Just split and get the third result

var string = "http://example.com/foldername/test.html"
console.log(string.split("/")[3])

Or using the pathname :

var string = "/foldername/test.html"
console.log(string.split("/")[1])

Solution 2:[2]

I would pass the URL to the URL() constructor to create a new instance. After that, you can access the pathname, split by the path separator, filter out empty and file names tokens, and recombine.

const pathJoin = (parts, sep) => {
   const separator = sep || '/', replace = new RegExp(`${separator}{1,}`, 'g');
   return parts.join(separator).replace(replace, separator);
}

const fullUrlPath = (url) => {
  if (typeof url === 'string') url = new URL(url);
  return pathJoin(url.pathname.split('/')
    .filter(path => path.trim() !== '' && !/^[\S]+\.[\S]+$/.test(path)));
};
  
console.log(fullUrlPath('http://example.com/foldername/test.html'));

Solution 3:[3]

Very easy and simple see

//check for folder
var foldername = (location.href).split("/")[3];

console.log(foldername);

Solution 4:[4]

You can use window.location.pathname.split('/')[1]

Solution 5:[5]

You already have the answer. You just need to work your pathname with something like:

window.location.pathname.split("/").map((folder)=>console.log(folder))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexandre Elshobokshy
Solution 2 Mr. Polywhirl
Solution 3 Grogu
Solution 4 MLFR2kx
Solution 5 Raphael M.