Categories
JavaScript Answers

How to extract parameter value from URL using regular expressions and JavaScript?

Spread the love

Sometimes, we want to extract parameter value from URL using regular expressions and JavaScript.

In this article, we’ll look at how to extract parameter value from URL using regular expressions and JavaScript.

How to extract parameter value from URL using regular expressions and JavaScript?

To extract parameter value from URL using regular expressions and JavaScript, we use the regex match method.

For instance, we write

const regex = /http\:\/\/www\.youtube\.com\/watch\?v=([\w-]{11})/;
const url = "http://www.youtube.com/watch?v=Ahg6qcgoay4";
const [, id] = url.match(regex);

to call url.match with the regex that has a capture group ([\w-]{11}) to get the value of the v query parameter.

Then we call url.match with regex to return an array with the video’s id as the 2nd value of the array.

Conclusion

To extract parameter value from URL using regular expressions and JavaScript, we use the regex match 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 *