LearnFrenzy
Sign in Take a free test

String Methods · String Methods Coding Problems · Question 9

Parse a URL query string in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Parse "?q=java%20script&page=2&tag=js&tag=css&debug" into an object (decode values, repeated keys become arrays, keys without values become true), then compare with URLSearchParams.

Solution
main.js
function parseQuery(qs) {
  const result = {};
  for (const part of qs.replace(/^\?/, "").split("&").filter(Boolean)) {
    const [rawKey, rawValue] = part.split("=");
    const key = decodeURIComponent(rawKey);
    const value = rawValue === undefined ? true : decodeURIComponent(rawValue.replace(/\+/g, " "));
    if (key in result) result[key] = [].concat(result[key], value);
    else result[key] = value;
  }
  return result;
}

const qs = "?q=java%20script&page=2&tag=js&tag=css&debug";
console.log(parseQuery(qs));
const params = new URLSearchParams(qs);
console.log(params.get("q"), params.getAll("tag"), params.has("debug"));

Output Verified by running it on Node.js

{ q: 'java script', page: '2', tag: [ 'js', 'css' ], debug: true }
java script [ 'js', 'css' ] true

Each key=value pair is split once; decodeURIComponent turns %20 back into a space. [].concat(existing, value) turns a repeated key into an array. In real code the built-in URLSearchParams does all of this.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links