How to get the file name from page URL using JavaScript ? (original) (raw)
Last Updated : 25 Jun, 2024
JavaScript provides multiple techniques for string manipulation and pattern matching. By demonstrating various methods, the article equips developers with versatile solutions to dynamically retrieve and utilize file names from different URL formats within their applications.
There are several approaches to getting the file name from the page URL using JavaScript which are as follows:
Table of Content
Using window.location.pathname
This approach utilizes the window.location.pathname property to fetch the path of the current URL and extracts the file name by splitting the path using the `/` delimiter and retrieving the last segment.
**Example: To demonstrate extracting file names from page URLs using JavaScript.
HTML `
Get File Name from URLGet File Name Example
Get File NameFile Name:
`
**Output:
Output
Using URL Object
The URL object provides a structured way to parse URLs. This approach creates a URL object with the current URL and retrieves the pathname, then extracts the file name similarly.
**Example: To demonstrate extracting file name from page URL using JavaScript.
HTML `
Get File Name from URLGet File Name Example
Get File NameFile Name:
`
**Output:
Output
Using split() Method
This approach splits the URL path by `/` and retrieves the last element of the resulting array, which represents the file name.
**Example: To demonstrate extracting file name from page URL using JavaScript.
HTML `
Get File Name from URLGet File Name Example
Get File NameFile Name:
`
**Output:
Output
Using Regular Expressions
Regular expressions can be used to match and capture the file name from the URL path, providing flexibility for more complex URL structures.
**Example: To demonstrate extracting file name from page URL using JavaScript.
HTML `
Get File Name from URLGet File Name Example
Get File NameFile Name:
`
**Output:
Output