Reading Query Strings Manually
You'll learn: How to extract query parameters from location.search using basic string methods when you can't or don't want to use built-in URL parsing.
What Are Query Strings?
When you look at a URL like https://example.com/search?q=pizza&sort=rating, the part after the ? is called the query string. It contains key-value pairs separated by & symbols. Sometimes you need to parse these manually using just JavaScript string operations.
Why Parse Manually?
Before modern APIs, developers had to parse query strings by hand. Even today, understanding this technique helps you grasp how URLs work under the hood and gives you more control when needed.
The Basic Approach
The location.search property gives you the raw query string, including the leading ?. To extract parameters:
- Remove the
?from the start - Split the string by
&to get individual pairs - Split each pair by
=to separate keys from values - Decode any URL-encoded characters
// location.search is "?q=pizza&sort=rating"
const queryString = location.search.slice(1); // Remove '?'
const pairs = queryString.split('&'); // ['q=pizza', 'sort=rating']
const params = {};
pairs.forEach(pair => {
const [key, value] = pair.split('=');
params[decodeURIComponent(key)] = decodeURIComponent(value);
});
console.log(params); // { q: 'pizza', sort: 'rating' }
Handling Edge Cases
Remember to use decodeURIComponent() to convert encoded characters like %20 (space) back to readable form.
Key Takeaway: You can manually parse query strings by using slice() to remove the ?, split() to break apart key-value pairs, and decodeURIComponent() to decode special characters—giving you full control over URL parameter extraction.