Sometimes, we want to use a regex to match filename at end of URL with JavaScript.
In this article, we’ll look at how to use a regex to match filename at end of URL with JavaScript.
How to use a regex to match filename at end of URL with JavaScript?
To use a regex to match filename at end of URL with JavaScript, we can use the JavaScript regex exec method.
For instance, we write:
const fileName = /[^/]*$/.exec('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf')
console.log(fileName)
We use the /[^/]*$/ regex to match the part of the URL after the last slash.
Then we call exec with a URL to return the match.
As a result, fileName is ['dummy.pdf', index: 62, input: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf', groups: undefined]
Conclusion
To use a regex to match filename at end of URL with JavaScript, we can use the JavaScript regex exec method.
