By using JavaScript’s search property, you can easily retrieve data from URL query parameters. This article explains how.
Please tell me how to obtain URL query information using the search property.
The search property is used to retrieve the query string from the current window’s URL.
Also, the URLSearchParams object is an object for handling retrieved query strings, and you can use the get method to retrieve parameter values.
What is the search property?
The search property in JavaScript is one of the Window objects and is used to retrieve information in the query string portion from the URL of the currently displayed Web page.
The query string begins with a ? The search property allows JavaScript to handle the query string retrieved from the URL.
How to get information about the query string part
The following is sample code using the SEARCH property. This code outputs the query string retrieved from the current URL to the console.
const queryString = window.location.search;
console.log(queryString);
The above code uses window.location.search to retrieve the query string portion from the URL of the currently displayed Web page. The query string obtained is stored in a variable named queryString. Then, console.log() is used to output the queryString to the console.
To be more specific, the URL is https://example.com/?name=John&age=30の場合, the queryString is stored as ?name=John&age=30, and the console displays ?name=John&age=30.
Explanation using a sample program
The JavaScript Window object contains URL information for the current window. From this URL information, you can easily obtain URL query information by using the search property.
// URL: http://example.com/?name=John&age=25
const queryString = window.location.search;
console.log(queryString); // "?name=John&age=25"
const urlParams = new URLSearchParams(queryString);
console.log(urlParams.get('name')); // "John"
console.log(urlParams.get('age')); // "25"
In this example, window.location.search is used to retrieve a query string from the current URL, and the URLSearchParams object is used to retrieve values from the retrieved query string. The get method can be used to retrieve the value of a specified parameter.
summary
We explained how to use the search property to retrieve data from URL query parameters.
- You can use window.location.search to get a query string from the current URL.
- URLSearchParams objects can be used to retrieve values from retrieved query strings.
- The get method can be used to retrieve the value of a given parameter.
You use the URLSearchParams object to retrieve and use values from the query string you get!
By using JavaScript’s search property, you can retrieve information from the query string portion of the URL of the currently displayed Web page and handle it in JavaScript. Query strings are often used to convey parameters used in websites, and learning how to use the search property will allow you to develop more flexible web applications.
Comments