URLSearchParams and repeated query keys
Quick answer
URLSearchParams represents ordered query name/value pairs. It handles form-style percent encoding and supports repeated names.
How it works
get returns the first matching value or null; getAll returns every value. append adds an entry; set replaces the first and removes other matching entries. toString serializes without a leading question mark. Spaces serialize as plus signs; literal plus signs are encoded. Use URL.searchParams to update the URL itself.
Local examples
Run in a fresh browser document; no external network is needed. The actual ByteMind editor is unverified.
(async () => {const p=new URLSearchParams("tag=a&tag=b");p.append("tag","c");console.log(p.get("tag"),JSON.stringify(p.getAll("tag")));})()Expected console output:
a ["a","b","c"]get reads the first entry while getAll preserves repeats.
Run in a fresh browser document; no external network is needed. The actual ByteMind editor is unverified.
(async () => {const u=new URL("https://example.test/?q=old&q=other");u.searchParams.set("q","a+b c");console.log(u.searchParams.toString(),u.search);})()Expected console output:
q=a%2Bb+c ?q=a%2Bb+cset removes duplicate q entries and serializes the value.
Common mistakes
Do not concatenate raw user input into a query. Parameters are strings and still require domain validation.
Guided practice
Build a search query with two tag values and a search term containing a space and plus sign.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
URLSearchParams and repeated query keys — Knowledge Check
Apply the concept and reason about the example output.
Which method retrieves all repeated query values?
Which method adds a duplicate name without deleting old entries?
Does toString include the initial question mark?
What is the expected console output of URLSearchParams and repeated query keys example 1?
(async () => {const p=new URLSearchParams("tag=a&tag=b");p.append("tag","c");console.log(p.get("tag"),JSON.stringify(p.getAll("tag")));})()What is the expected console output of URLSearchParams and repeated query keys example 2?
(async () => {const u=new URL("https://example.test/?q=old&q=other");u.searchParams.set("q","a+b c");console.log(u.searchParams.toString(),u.search);})()