URL parsing
string manipulation
key-value extraction
programming tips
web development

Best way to parse URL string to get values for keys?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Extracting query parameter values from a URL is one of the most common tasks in web development. Every major language provides built-in URL parsing utilities that handle encoding, edge cases, and multi-valued parameters correctly. Avoid writing custom split-and-loop parsers when standard libraries exist.

JavaScript (Browser and Node.js)

The URL and URLSearchParams APIs work in all modern browsers and Node.js 10+.

javascript
1const raw = "https://example.com/search?q=hello+world&page=3&lang=en&lang=fr";
2const url = new URL(raw);
3
4// Single value
5console.log(url.searchParams.get("q"));     // "hello world"
6console.log(url.searchParams.get("page"));  // "3"
7
8// Multi-valued parameter
9console.log(url.searchParams.getAll("lang")); // ["en", "fr"]
10
11// Check existence
12console.log(url.searchParams.has("q"));     // true
13console.log(url.searchParams.has("missing")); // false
14
15// Iterate all parameters
16for (const [key, value] of url.searchParams) {
17  console.log(`${key} = ${value}`);
18}

URLSearchParams automatically decodes percent-encoded values and handles + as space.

Python

Python's urllib.parse module provides urlparse and parse_qs for reliable URL decomposition.

python
1from urllib.parse import urlparse, parse_qs
2
3raw = "https://example.com/search?q=hello+world&page=3&lang=en&lang=fr"
4parsed = urlparse(raw)
5
6print(parsed.scheme)   # "https"
7print(parsed.netloc)   # "example.com"
8print(parsed.path)     # "/search"
9
10params = parse_qs(parsed.query)
11print(params["q"])      # ["hello world"]
12print(params["page"])   # ["3"]
13print(params["lang"])   # ["en", "fr"]
14
15# parse_qs always returns lists — use [0] for single values
16page = params.get("page", ["1"])[0]
17print(int(page))  # 3

Use parse_qs (returns lists) rather than parse_qsl (returns flat tuples) when you need multi-valued parameter support.

PHP

PHP's parse_url and parse_str handle URL decomposition.

php
1$raw = "https://example.com/search?q=hello+world&page=3&lang=en";
2$parts = parse_url($raw);
3
4echo $parts['scheme'];  // "https"
5echo $parts['host'];    // "example.com"
6echo $parts['path'];    // "/search"
7
8parse_str($parts['query'], $params);
9echo $params['q'];      // "hello world"
10echo $params['page'];   // "3"

Go

Go's net/url package parses URLs and query parameters into a Values map.

go
1package main
2
3import (
4    "fmt"
5    "net/url"
6)
7
8func main() {
9    raw := "https://example.com/search?q=hello+world&page=3&lang=en&lang=fr"
10    u, err := url.Parse(raw)
11    if err != nil {
12        panic(err)
13    }
14
15    params := u.Query()
16    fmt.Println(params.Get("q"))       // "hello world"
17    fmt.Println(params.Get("page"))    // "3"
18    fmt.Println(params["lang"])        // ["en", "fr"]
19}

Query() returns url.Values, which is map[string][]string. Use Get() for the first value or index the map directly for all values.

C# / .NET

Use System.Uri with HttpUtility.ParseQueryString or the newer QueryHelpers in ASP.NET Core.

csharp
1using System;
2using System.Web;
3
4var raw = "https://example.com/search?q=hello+world&page=3";
5var uri = new Uri(raw);
6var query = HttpUtility.ParseQueryString(uri.Query);
7
8Console.WriteLine(query["q"]);    // "hello world"
9Console.WriteLine(query["page"]); // "3"
10Console.WriteLine(query["missing"]); // null

Handling Edge Cases

Several URL parsing pitfalls apply across all languages:

python
1from urllib.parse import parse_qs
2
3# Empty value: ?key= gives key with empty string
4print(parse_qs("key="))            # {'key': ['']}
5
6# No value: ?key gives key with empty string
7print(parse_qs("key", keep_blank_values=True))  # {'key': ['']}
8
9# Encoded characters: %20 and + both decode to space
10print(parse_qs("q=hello%20world"))  # {'q': ['hello world']}
11print(parse_qs("q=hello+world"))    # {'q': ['hello world']}
12
13# Fragment is NOT part of query string
14# In "?q=test#section", the fragment "#section" is separate

Common Pitfalls

  • Writing manual split("&") and split("=") parsers that break on encoded = or & characters inside values.
  • Forgetting that parse_qs returns lists, not single values, and accessing the result as a string.
  • Confusing URL fragment (#section) with query parameters — fragments are never sent to the server.
  • Not handling multi-valued parameters (same key appearing multiple times like ?tag=a&tag=b).
  • Assuming query parameter order is guaranteed — it is not part of the URL specification.

Summary

  • Use URLSearchParams in JavaScript, parse_qs in Python, parse_url/parse_str in PHP, url.Parse in Go, and HttpUtility.ParseQueryString in C#.
  • Standard libraries handle percent-encoding, + spaces, and multi-valued parameters correctly.
  • Always use get with a default value for optional parameters.
  • Never write custom string-splitting parsers for URL query strings in production code.
  • Remember that parse_qs returns lists — index [0] for single-value access.

Course illustration
Course illustration

All Rights Reserved.