Categories
JavaScript Answers

How to obtain the query string from the current URL with JavaScript?

Spread the love

Sometimes, we want to obtain the query string from the current URL with JavaScript.

In this article, we’ll look at how to obtain the query string from the current URL with JavaScript.

How to obtain the query string from the current URL with JavaScript?

To obtain the query string from the current URL with JavaScript, we can use the URL constructor.

For instance, we write

const params = new URL(document.location).searchParams;
const name = params.get("name");

to get the current URL with document.location to get a URL object from the current location object.

Then we use the searchParams property to get the query string from the current URL.

Next, we call get with the query parameter key to return the value of the query parameter with the given key.

Conclusion

To obtain the query string from the current URL with JavaScript, we can use the URL constructor.

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 *