How To Get Page Name From Url In Javascript

Getting the page name from a URL in JavaScript can be useful in various scenarios, such as tracking page views or displaying dynamic content based on the current page URL. In this tutorial, we will walk you through the steps to get the page name from a URL using JavaScript.

Steps:

1. Create a variable to store the current page URL: https://www.example.com/articles/my-article.html

2. Use the JavaScript method split() to split the URL into an array of strings based on the forward slash:

3. Retrieve the last item in the array, which is the page name:

4. If the page name contains any query parameters or file extensions, use the JavaScript method split() again to remove them:

5. Use the variable cleanPageName in your code for further manipulation or display.

You can test the code on a sample URL such as “https://example.com/blog/how-to-get-page-name-from-url-in-javascript”.

In conclusion, getting the page name from a URL in JavaScript is fairly simple and can be useful in various scenarios. Remember to split the URL into an array of strings and retrieve the last item, then clean up the page name as needed. Happy coding!

Full code: