How to get the FileName from Url in JavaScript

← PrevNext →

A URL or a web address, often has a file name, with few parameters occasionally. Sometimes, we might need to know only the file name in the URL. There's a simple technique to extract the file name from a url in JavaScript.

Top post on this topic: How to replace a String with another String in the URL Bar using JavaScript or jQuery

We want the file name from the url. But, first we need a url. You can use window.location.href to get the url of the current page or you can simply use the complete web address.

<script>
    let url = window.location.href;
    alert (url);
</script>
Try it

The alert will show the complete url (the web address), which will have the file name and few parameter etc. To get only the file name, I'll use the split() and pop() functions.

<script>
    let url = window.location.href;
    let filename = url.split('/').pop();
    alert (filename);
</script>
Try it
The split() function creates an array of string, after removing all the forward slash (/) from the url string. The pop() function will return the last element, which is file name, from the array. And that's what we want.

Related Post: How to check if the URL bar contains a Specified String in JavaScript and jQuery

Things get a little tricky, when the url has parameters (also called query strings or variables) and other information. A url with query string may look like this.

https://www.encodedna.com/javascript/practice-ground/default.htm?pg= accordion_menu_using_jquery_css

The above (second) example will not be able to return the file name in this case. Because the split() in the second example, removes the forward slashes only. The query string now have a question mark (?). We need to get rid of this too. Here's how we can do this.

<script>
    let url = window.location.href;
    let filename = url.split('/').pop().split('?')[0];
    alert (filename);
</script>
Try it
Now, it will split, pop and split again, to get the file name. Similarly, the url may have multiple parameters separated by &, it may # and lots of other information. In such cases, you might have to use the split() function multiple times.
<script>
    var url = window.location.href;
    var filename = url.split('/').pop().split('?')[0].split('#')[0];
    alert (filename);
</script>

Also Read: How to pass multiple variables or parameters using a QueryString in Asp.Net

That's it. Thanks for reading.

← PreviousNext →


Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.
Delivered by FeedBurner