Open In App

How to get the file name from page URL using JavaScript ?

Suppose you have given an HTML page and the task is to get the file name of an HTML page with the help of JavaScript. There are two approaches that are discussed below:

Approach 1: In this approach, window.location.pathname returns the relative URL of the page. Use split() method to split the URL on “/” and pop() method to get the last item from the array.

Approach 2: In this approach, location.pathname returns the relative URL of the page. Use lastIndexOf() method to get the last “/” and substring() method to get the item after “/” from the string.


Article Tags :