Get query string parameters from URL in JavaScript
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 then perform the other logic. So in this article, we will give you a simple function that will help you to get the value of query string parameters.
javascript get all url parameters, javascript get url parameter value by name, jquery get query string value from url, jquery get query string parameter, get query string in javascript on page load, javascript get url parameter w3schools, get url parameters javascript, jquery get url parameter.
Checkout more articles on JavaScript
Let’s create a simple function to get query string parameter value from the URL.
1 2 3 4 5 6 7 8 9 | 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 decode 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.
1 2 3 4 5 6 7 | var url = 'https://www.cluemediator.com/?search=login%20app&category=reactjs'; getQueryStringParams('search', url); // Output: login app getQueryStringParams('category', url); // Output: reactjs |
That’s it for today.
Thank you for reading. Happy Coding!