Home  >  Article  >  location.search usage

location.search usage

DDD
DDDOriginal
2023-06-25 16:42:561963browse

How to use location.search: 1. Get the query string; 2. Parse the query string; 3. Add query parameters; 4. Modify the query parameters.

location.search usage

#location.search is an attribute used to obtain the query string of the current page. The query string refers to the part after the question mark in the URL, in the form of key-value pairs. For example, for the URL "https://www.example.com/?name=John&age=25", the query string is "?name=John&age=25".

The following are some common methods of using location.search:

1. Get the query string: Use location.search to get the query string of the current page. It can be assigned to a variable and then further manipulated.

javascript
var query = location.search;
console.log(query); // 输出: ?name=John&age=25

2. Parse the query string: The query string can contain multiple key-value pairs, and we can use the URLSearchParams object to parse the query string.

javascript
var query = location.search;
// 创建URLSearchParams对象并传入查询字符串
var params = new URLSearchParams(query);
// 获取特定键的值
var name = params.get('name');
console.log(name); // 输出: John
var age = params.get('age');
console.log(age); // 输出: 25

3. Add query parameters: We can use the append() method of the URLSearchParams object to add query parameters.

javascript
var params = new URLSearchParams();
params.append('name', 'John');
// 将查询参数添加到URL中
location.search = params.toString();
console.log(location.search); // 输出: ?name=John

4. Modify query parameters: By modifying the properties of the URLSearchParams object, you can modify the value of the query parameters.

javascript
var params = new URLSearchParams(location.search);
// 修改特定键的值
params.set('age', '30');
// 更新URL
location.search = params.toString();
console.log(location.search); // 输出: ?name=John&age=30

The above is the detailed content of location.search usage. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn