URLSearchParams.sort Orders Query Keys

Canonicalize query strings with URLSearchParams.prototype.sort, which orders keys by UTF-16 code units while keeping duplicate key values in relative order.

JavascriptData Fetching

Code

javascriptsnippet
13 lines
const query = new URLSearchParams('sort=desc&tag=es2024&page=2&tag=intl&A=1');

// sort() mutates in place using UTF-16 code unit order (uppercase 'A' precedes 'page')
query.sort();
console.log('canonical:', query.toString());

// Duplicate keys preserve their original relative insertion order ('es2024' before 'intl')
console.log('tag order:', JSON.stringify(query.getAll('tag')));

// Compare two differently ordered queries after sorting both
const other = new URLSearchParams('page=2&tag=es2024&A=1&tag=intl&sort=desc');
other.sort();
console.log('same canonical key:', query.toString() === other.toString());

Output

Captured from a sandboxed run of this snippet in the build pipeline.

canonical: A=1&page=2&sort=desc&tag=es2024&tag=intl
tag order: ["es2024","intl"]
same canonical key: true

Stepwise trace — URLSearchParams.sort Orders Query Keys

The file’s state is a handful of top-level bindings: query, other.

What to watch for

  • Every call invokes built-in standard runtime primitives with no external crates.

Applying it

The run emits 3 labeled sections — canonical:, tag order:, same canonical key: — one per step.

Statements that matter

query.sort();
other.sort();

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. Its state lives in module-level bindings: `query`, `other`.