New urlsearchparams window location search
A great topic!
URLSearchParams
is a modern API for working with query strings in JavaScript. It allows you to easily parse and manipulate URL query strings.
window.location.search
is a property that returns the query string of the current URL.
Here's how you can use URLSearchParams
with window.location.search
:
Parsing the query string
const searchParams = new URLSearchParams(window.location.search);
This creates a new URLSearchParams
object and populates it with the query string from the current URL.
Accessing query string parameters
const param1 = searchParams.get('param1'); // returns the value of 'param1' if it exists
const param2 = searchParams.getAll('param2'); // returns an array of values for 'param2'
You can use the get()
method to retrieve a single value for a parameter, or the getAll()
method to retrieve an array of values for a parameter.
Setting query string parameters
searchParams.set('param3', 'value3');
searchParams.append('param4', 'value4');
You can use the set()
method to set a new value for a parameter, or the append()
method to add a new value to an existing parameter.
Updating the query string
window.location.search = searchParams.toString();
Once you've modified the URLSearchParams
object, you can update the query string of the current URL by assigning the toString()
method to window.location.search
.
Here's an example of how you might use these methods together:
const searchParams = new URLSearchParams(window.location.search);
const param1 = searchParams.get('param1');
if (!param1) {
searchParams.set('param1', 'default value');
}
window.location.search = searchParams.toString();
This code retrieves the value of param1
from the query string, sets a default value if it doesn't exist, and then updates the query string with the new value.