Categories
JavaScript Answers

How to use a regex to get first word after slash in URL with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *