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.
Code
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: trueStepwise 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
GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.