• Post category:JavaScript
  • Reading time:3 mins read

Today we’ll show you how to get query string parameters from URL in JavaScript.

Sometimes we need to get the query string value from the URL and perform the other logical operation. So in this article, we will give you a simple function that will help you to get the value of query string parameters.

Let’s create a simple function to get query string parameter value from the URL.

function getQueryStringParams(params, url) {
  // first decode URL to get readable data
  var href = decodeURIComponent(url || window.location.href);
  // regular expression to get value
  var regEx = new RegExp('[?&]' + params + '=([^&#]*)', 'i');
  var value = regEx.exec(href);
  // return the value if exist
  return value ? value[1] : null;
};

In the above function, first we decoded the URL and also consider the window.location.href if the url does not pass in the function.

Also we used the regular expression to get the query string parameter value and if value does not exist then we are returning the null value.

It’s time to check the function. Check the following code.

var url = 'https://www.codepremix.com/?search=spread%20operator&category=javascript';

getQueryStringParams('search', url);
// Output: spread operator

getQueryStringParams('category', url);
// Output: javascript

That’s it for today.
Thank you for reading. Happy Coding!

Leave a Reply