Better way of getting queryString params of a URL on FreeMarker

Viewed 204

Is there a better way of reading query string params values on FreeMarker, I have a URL, for example: http://test.com/user?testp1=123&testp2=2541 and I created the function below to read these query params:

Script

function testParams() {
  const params = new URLSearchParams(window.location.search);
  const testp1 = params.get('testp1');
  const testp2 = params.get('testp2');
  document.getElementById("testp1").value = testp1;
  document.getElementById("testp2").value = testp2;

}
window.onload = testParams;
<input type="text" name="testp1" id="testp1" />
<input type="text" name="testp2" id="testp2" />

So when the page loads it reads these query params and set them to its respective fields.

1 Answers

Iterate over all your params and retrieve the key and value:

function testParams() {
  // Demo hardcoded string, you use window.location.search
  const params = new URLSearchParams("testp1=123&testp2=2541"); 
  [...params].forEach(([key, val]) => document.getElementById(key).value = val);
}
window.addEventListener("load", testParams);
<input type="text" name="testp1" id="testp1" />
<input type="text" name="testp2" id="testp2" />

Also, read: URLSearchParams.entries()

Related