Query String
The part of a URL that contains data to be passed to web applications, appearing after the question mark (?) as key-value pairs.
Overview
Query strings are a way to pass data in URLs using key-value pairs. They appear after the ? character and are commonly used to send parameters to web pages, filter data, track analytics, or maintain state across page loads. Query strings are particularly useful for sharing URLs with specific application states.
Example
javascript// Example URL with query string // https://example.com/search?q=javascript&page=2&sort=recent // Vanilla JavaScript - Read query string const urlParams = new URLSearchParams(window.location.search); const query = urlParams.get('q'); // 'javascript' const page = urlParams.get('page'); // '2' const sort = urlParams.get('sort'); // 'recent' // Check if parameter exists if (urlParams.has('sort')) { console.log('Sort parameter present'); } // Get all values for a parameter const tags = urlParams.getAll('tag'); // ['js', 'web', 'dev'] // Building query strings const params = new URLSearchParams({ q: 'react', page: '1', limit: '20' }); const url = `https://api.example.com/search?${params.toString()}`; // https://api.example.com/search?q=react&page=1&limit=20 // Adding to existing URL const newParams = new URLSearchParams(window.location.search); newParams.set('page', '3'); window.history.pushState({}, '', `?${newParams.toString()}`); // React example - reading query params import { useSearchParams } from 'react-router-dom'; function SearchPage() { const [searchParams, setSearchParams] = useSearchParams(); const query = searchParams.get('q'); const page = searchParams.get('page') || '1'; const updateSearch = (newQuery) => { setSearchParams({ q: newQuery, page: '1' }); }; return <div>Searching for: {query}</div>; } // Next.js example import { useRouter } from 'next/router'; function Page() { const router = useRouter(); const { q, page } = router.query; return <div>Query: {q}, Page: {page}</div>; }
Key Points
- Appears after ? in URL
- Format: key=value&key2=value2
- Use URLSearchParams API for parsing
- Values are always strings
- Special characters must be URL-encoded
Learn More
- Routing - Client-side routing
- URL - URL handling
- MDN: URLSearchParams