window.location.search javascript

Understanding window.location.search in JavaScript

As a web developer, you might have come across the term window.location.search while working with JavaScript. This property returns the query string part of the URL, including the question mark (?), and allows you to extract specific parameters from the URL.

Example Usage

Let's say you have a URL like this: https://example.com?name=Raju&age=25. To extract the values of name and age parameters, you can use the following code:

const params = new URLSearchParams(window.location.search);
const name = params.get('name');
const age = params.get('age');

console.log(name); // Raju
console.log(age); // 25

In the above code, we first create a new instance of URLSearchParams by passing the result of window.location.search. Then, we use the get() method to retrieve the value of each parameter.

Other Methods

URLSearchParams also provides other methods to work with query strings:

  • has(name): Returns a boolean indicating whether a parameter with the given name exists in the query string.
  • set(name, value): Sets the value of a parameter with the given name. If it already exists, it replaces the value.
  • delete(name): Removes a parameter with the given name from the query string.
  • append(name, value): Adds a new parameter with the given name and value to the query string.
  • toString(): Returns a string representation of the query string.

Conclusion

The window.location.search property is a powerful tool for working with query strings in JavaScript. By using the URLSearchParams object, you can easily extract, manipulate, and generate query strings without having to deal with the tedious parsing and encoding of URL components.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe