Getting the query parameters out of a URL string by using vanilla Javascript.
The query parameters are what is used in HTTP GET to shape a response.
The main piece to this code is the self-made function that puts the query parameters and values into an array.
This works by using URLSearchParams to get the keys from the URL string and then the value for that key.
These are pushed into a multidimensional array which is returned.
function URLQueryAsArray(str) { let params = new URLSearchParams(str); let params_array = []; for (let value of params.keys()) { params_array.push([value, params.get(value)]); } return params_array; }
The other function is what gets called when a URL is placed into the text input. It calls URLQueryAsArray() and builds the output
function updateParams(val) { document.getElementById("output-div").innerHTML = ""; let split_url = val.split("?"); let query_string = split_url[1]; let p_array = URLQueryAsArray(query_string); let output_div = document.getElementById("output-div"); for (let index = 0; index < p_array.length; ++index) { let p_string = p_array[index][0] + " => " + p_array[index][1]; let newNode = document.createElement("p"); newNode.innerHTML = p_string; output_div.appendChild(newNode); } }
The basic HTML:
<h3>URL GET and value parameters</h3> <p><b>Try with:</b> https://stats.nba.com/stats/teamgamelog?DateFrom=&DateTo=&LeagueID=00&Season=2020-21&SeasonType=Playoffs&TeamID=1610612749</p> <form style="padding-top: 1rem;"> <label for="url">URL: </label> <input id="url" type="text" onkeyup="updateParams(this.value);" /> </form> <div id='output-div'> </div>
The CodePen: