In this post, we will how to get query string form current URL in JavaScript. If you don't know about query string, then definition of query string is as follows:  A query string is a part of a URL that assigns values to specified parameters.


For example we have the following URL :


https://www.codexradar.com/search?q=hello code-box


In this above URL the query string is  ?q=hello where q is a parameter and its value is hello.


How To Get Query String From URL in JavaScript ?


Get Query String From URL in JavaScript

To get query string from URL in JavaScript, we follow the following steps:

  • To get only query string part of the URL we use window.location.search property. Then we store it in a variable called queryString. We get ?q=hello
  • Then we use URLSearchParam api to access the value of the query.
  • After this we have to check if a parameter was null or not.
  • Then we get the value of query string parameter.


The complete code is given below:


<!DOCTYPE html>
<html>
<body>

<h1>How To Get Query String From URL in JavaScript ?</h1>

<script>
var queryString = window.location.search;
var urlParamsArr =new URLSearchParams(queryString);
var q = urlParamsArr.get('q');
if(q!=null) {
console.log(q);
}
</script>

</body>
</html> code-box

Summary

In this post we learn how to get query string parameter value form URL in JavaScript. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts.

Post a Comment

Previous Post Next Post