Logo

How to get parameter value from query string?

Query strings are a common way to pass parameters in a URL—like ?id=123&name=John. Whether you’re building a single-page application or a traditional server-rendered page, you’ll often need to extract these parameters to access user-specific information or customize the page. Below, we’ll explore straightforward ways to retrieve these query parameter values using both modern and legacy approaches in JavaScript.

1. Using URLSearchParams (Modern Approach)

If you’re working in modern browsers or Node.js (version 10 and above), you can use the built-in URLSearchParams API to parse and read query parameters with minimal fuss.

// Assuming URL is: https://example.com/?id=123&name=John const urlParams = new URLSearchParams(window.location.search); const id = urlParams.get('id'); // "123" const name = urlParams.get('name'); // "John" console.log(id, name);

How It Works

  1. Create a URLSearchParams object using window.location.search—the part of the URL including the ? and everything following it.
  2. Use .get('paramName') to retrieve the value of a specific parameter.
  3. Check for existence with .has('paramName') if you’re uncertain whether the parameter is present.

This method gracefully handles empty or missing parameters and is currently the most recommended approach for modern JavaScript applications.

2. Manually Parsing the Query String (Legacy Approach)

Older browsers (pre-IE10) or certain legacy systems may not support URLSearchParams. In these cases, you can manually split and parse the query string:

function getQueryParam(param) { const queryString = window.location.search.substring(1); // "id=123&name=John" // Convert "id=123&name=John" into ["id=123", "name=John"] const paramsArray = queryString.split('&'); for (let i = 0; i < paramsArray.length; i++) { const [key, value] = paramsArray[i].split('='); if (key === param) { return decodeURIComponent(value); } } return null; // if param not found } // Usage: const id = getQueryParam('id'); // "123" const name = getQueryParam('name'); // "John"

Important Details

  • substring(1) removes the leading ? from the query string.
  • Splitting by & breaks it into key-value pairs, then splitting by = extracts the key and value.
  • decodeURIComponent ensures any encoded spaces or symbols are properly decoded.

This method is more verbose than URLSearchParams, but it works in environments lacking the modern API.

3. Retrieving Query Params on the Server Side (Node.js)

If you’re building a server with Node.js or using frameworks like Express, you often read query parameters from the incoming request object.

Example with Express:

app.get('/users', (req, res) => { const userId = req.query.id; // "123" const userName = req.query.name; // "John" // Perform actions with userId or userName... res.send(`User ID: ${userId}, Name: ${userName}`); });

On the server side, Express automatically parses the query string into a req.query object, making it easy to access parameters by name.

4. Tips and Best Practices

  1. Validate User Input
    Any data from the query string can be manipulated by users or malicious actors. Always validate and sanitize inputs, especially in server-side code.

  2. Handle Special Characters
    Use encodeURIComponent and decodeURIComponent to ensure data with spaces, ampersands (&), or other special characters is handled correctly.

  3. Multiple or Missing Parameters

    • If a parameter might appear multiple times (e.g., &tag=apple&tag=banana), consider how you want to handle an array of values. URLSearchParams.getAll('tag') can retrieve all matches.
    • If parameters may be missing, always check for null or undefined before using them in logic.
  4. Stay Up to Date
    Modern JavaScript features like URLSearchParams are widely supported but might need polyfills in older environments. Check browser compatibility or Node.js versions to confirm.

Mastering JavaScript and Beyond

Parsing query strings is just one small piece of building robust, user-friendly applications. If you’re looking to strengthen your JavaScript skills and ensure your code is both elegant and efficient, consider these courses from DesignGurus.io:

For a more hands-on way to fine-tune your skills, try Coding Mock Interviews with ex-FAANG engineers. Personalized feedback can help you tackle interview challenges confidently and land top-tier roles.

Conclusion

Getting parameter values from a query string is a fundamental yet essential task. Modern JavaScript environments provide a convenient URLSearchParams API, but you can also parse manually or rely on server-side frameworks like Express for parameter management. Whichever approach you use, remember to validate inputs and handle special characters to keep your application secure and user-friendly. With these strategies—and a growing mastery of JavaScript—you’ll be well-prepared to build polished, high-performing applications. Happy coding!

CONTRIBUTOR
TechGrind