The Location.search
property in JavaScript is a string that represents the query string part of a URL. It includes the characters after the ?
symbol in the URL and contains key-value pairs separated by the &
symbol.
Here’s an example of how you could use the Location.search
property:
// Assume the current URL is:
// http://example.com?name=John&age=30
const queryString = window.location.search;
console.log(queryString); // "?name=John&age=30"
In this example, we access the Location.search
property and store it in the queryString
variable. We then log the queryString
to the console.
To access the values of the key-value pairs in the query string, you could use the URLSearchParams
class. This class provides a convenient way to parse and access the values of the query string.
Here’s an example:
// Assume the current URL is:
// http://example.com?name=John&age=30
const queryString = window.location.search;
const searchParams = new URLSearchParams(queryString);
const name = searchParams.get('name');
const age = searchParams.get('age');
console.log(name); // "John"
console.log(age); // "30"
In this example, we create an instance of the URLSearchParams
class by passing the queryString
to its constructor. We then use the get()
method to retrieve the values of the name
and age
keys in the query string. The values are logged to the console.
+ There are no comments
Add yours