Web Development
Query String
URL Parameters
Programming
Coding Tips

How to get parameter value from query string?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Query strings are a fundamental part of URL design and functionality in web development, often used to pass data between web pages. They appear at the end of a URL after a question mark (?) and consist of key-value pairs separated by ampersands (&). Extracting values from these strings is a ubiquitous task for web developers. This guide delves into various methods and considerations for retrieving parameter values from query strings across different programming environments.

Understanding Query Strings

A query string is a part of a URL where data is passed in the form of key-value pairs. For instance, in the URL http://example.com/page?name=john&age=25, the query string is name=john&age=25, with name and age as parameters.

Retrieving Query String Values in JavaScript

JavaScript, being the language of the web, offers straightforward methods to manipulate URLs and their components:

Using URLSearchParams

The URLSearchParams API provides a robust interface to work with query strings:

javascript
const params = new URLSearchParams(window.location.search);
const name = params.get('name'); // Returns 'john'

This method is highly recommended for modern web applications due to its simplicity and built-in browser support.

Manual Parsing

For educational purposes or environments where URLSearchParams is unsupported, manual parsing can be achieved:

javascript
1function getParameterByName(name, url = window.location.href) {
2    name = name.replace(/[\[\]]/g, '\\$&');
3    const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
4          results = regex.exec(url);
5    if (!results) return null;
6    if (!results[2]) return '';
7    return decodeURIComponent(results[2].replace(/\+/g, ' '));
8}

Techniques in Server-Side Languages

PHP

PHP populates query string parameters into the $_GET superglobal array automatically:

php
$name = $_GET['name']; // Gets 'john' from the query string

Node.js

With Node.js, you can use the url module in combination with the querystring module:

javascript
1const url = require('url');
2const querystring = require('querystring');
3
4const parsedUrl = url.parse('http://example.com/page?name=john&age=25');
5const queryParams = querystring.parse(parsedUrl.query);
6const name = queryParams.name; // 'john'

Security Considerations

When working with query strings, it's crucial to consider security implications, especially regarding data validation and sanitation to prevent XSS (Cross-Site Scripting) and other vulnerabilities.

Best Practices

  • Encoding Data: Always use proper encoding techniques like encodeURIComponent() in JavaScript when creating query strings programmatically.
  • Validation and Sanitization: Always validate and sanitize incoming parameters to prevent security vulnerabilities.
  • Use Libraries and Frameworks: When available, use established libraries and frameworks which handle most of the heavy lifting securely and efficiently.

Summary Table

MethodEnvironmentUse Case
URLSearchParamsModern BrowsersParsing and retrieving query string parameters
Manual ParsingAny JavaScriptLegacy support where URLSearchParams is unavailable
$_GET ArrayPHPAccessing query parameters in server-side PHP
url & querystringNode.jsParsing URL and query strings in a Node.js app

Conclusion

Understanding and manipulating query strings is essential for web developers. Modern methods like URLSearchParams simplify the process, while server-side techniques provide robust solutions for handling URL-encoded data in applications. Always keep in mind security best practices to protect your applications from potential threats.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions