Skip to content
the poor coder

window.location.search javascript

Poor Man
Published
Reading time
1 min read
On this page

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:

Text
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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC