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
1 |
const url = window.location.href; |
2. Use the JavaScript method split()
to split the URL into an array of strings based on the forward slash:
1 |
const parts = url.split('/'); |
3. Retrieve the last item in the array, which is the page name:
1 |
const pageName = parts[parts.length - 1]; |
4. If the page name contains any query parameters or file extensions, use the JavaScript method split()
again to remove them:
1 |
const cleanPageName = pageName.split('?')[0].split('.')[0]; |
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:
1 2 3 4 5 |
const url = window.location.href; const parts = url.split('/'); const pageName = parts[parts.length - 1]; const cleanPageName = pageName.split('?')[0].split('.')[0]; console.log(cleanPageName) |