← All Exercises

Read and Normalize Filter State from a Query String

basicjavascript~15min

Background

Filter interfaces store state in the URL so results are shareable; normalizing that state prevents duplicate tags and invalid pages.

Problem

Write readFilterState(search) that turns a query string into a normalized filter object with sorted unique tags, a whitelisted sort key, and a page number of at least one.

Input

A JSON string with a search property holding a query string.

Output

A JSON string with tags, sort, and page keys.

Sample tests

Sample 1

Input: {"search":"?tag=CSS&tag=html&tag=css&sort=popular&page=2"}
Expected: {"tags":["css","html"],"sort":"popular","page":2}

Sample 2

Input: {"search":"?sort=unknown&page=0"}
Expected: {"tags":[],"sort":"relevance","page":1}

Sample 3

Input: {"search":"?tag=%20a11y%20&tag="}
Expected: {"tags":["a11y"],"sort":"relevance","page":1}

Your solution

Learning objective

Use URLSearchParams to read multi-value query state and normalize it into a predictable filter model.