There is a simple method to get the query string parameters in javascript.
1const getQueryParams = (params, url) => {2 let href = url3 //this expression is to get the query strings4 let reg = new RegExp("[?&]" + params + "=([^&#]*)", "i")5 let queryString = reg.exec(href)6 return queryString ? queryString[1] : null7}89getQueryParams("data", "http://another-example.com?example=something&data=13")
Firstly, this function takes paramsand url as a parameters. Inside, the function we assign the url to varialble href.
After that, Regex Pattern checks the url to match a pattern. Mainly, regex checks the value that starts with either & or ? followed by the parameter that you pass.
Regex takes the value after symbol (=) and store it in the variable queryString and returns it.
Getting All Query Strings in Javascript
Above Implementation works fine if you want to get the specific query string. However, it will not work if you want to get all the query strings.
To get all the query strings from url, we can implement a different approach.
1const getQueryParams = url => {2 let queryParams = {}3 //create an anchor tag to use the property called search4 let anchor = document.createElement("a")5 //assigning url to href of anchor tag6 anchor.href = url7 //search property returns the query string of url8 let queryStrings = anchor.search.substring(1)9 let params = queryStrings.split("&")1011 for (var i = 0; i < params.length; i++) {12 var pair = params[i].split("=")13 queryParams[pair[0]] = decodeURIComponent(pair[1])14 }15 return queryParams16}1718getQueryParams("http://another-example.com?example=something&data=13")
Above all, the simplest way to solve this problem is to create an anchor element and use a property called search in anchor element. Searchproperty returns the queryStringcompletely.
Therefore, the above function takes url as a parameter. After that, we create an anchor element and assign the url to href.
After that, search method of anchor element returns the query strings of url.
As a result, we can get all the query parameters by splitting the string using keyword &.
Once you have the params in an Array, you can loop through it and get all the query strings that you want.
Comments
Post a Comment