Sometimes, we want to use a regex to get first word after slash in URL with JavaScript.
In this article, we’ll look at how to use a regex to get first word after slash in URL with JavaScript.
How to use a regex to get first word after slash in URL with JavaScript?
To use a regex to get first word after slash in URL with JavaScript, we can call the string’s replace
method.
For instance, we write:
const s = window.location.pathname.replace(/^\/([^\/]*).*$/, '$1');
console.log(s)
to call replace
on the current URL with a regex that gets the first word after the slash and returns it.
Conclusion
To use a regex to get first word after slash in URL with JavaScript, we can call the string’s replace
method.