URLSearchParams 类的 NodeJS urlSearchParams.get() 方法从查询字符串中的指定名称中检索值。
可以使用 URLSearchParams API 读取和写入 URL 的查询部分。此类在全局对象上也可用。
为了更好地理解这种方法,让我们看一个现实生活中的例子。请考虑此 URL ('https://www.youtube.com/watch?v=towpH780PT0'),其中 'v=towpH780PT0' 称为查询段。在此查询中,(v) 是名称,(towpH780PT0) 是值。它共同构成了一个名称-值对。
语法
以下是 NodeJS URLSearchParams.get() 方法的语法
URLSearchParams.get(name)
参数
name
:这指定了要返回的参数的名称。
返回值
此方法返回作为参数传递的给定名称的字符串值。
- 如果有多个具有给定名称的名称/值对,则此方法返回第一对中的值。
- 如果没有名称为 name 的对,则返回 null。
在以下示例中,我们尝试在查询字符串中获取名为“two”的键的值。
const url = require('node:url');
const MyUrl = new URL('https://www.qikepu.com?one=1&two=2&three=3');
console.log("URL: ", MyUrl.href);
const Params = new URLSearchParams('one=1&two=2&three=3');
console.log("Query string: " + Params);
console.log("Trying to get the value of key 'two'.....");
console.log("The value is: " + Params.get("two"));
输出
执行上述程序后,NodeJS get() 方法返回键“two”的值。
URL: https://www.qikepu.com/?one=1&two=2&three=3
Query string: one=1&two=2&three=3
Trying to get the value of key 'two'.....
The value is: 2
Query string: one=1&two=2&three=3
Trying to get the value of key 'two'.....
The value is: 2
例
如果要搜索的名称在查询字符串中多次出现,则 get() 方法将返回其第一次出现的值。
在下面的程序中,我们试图在查询字符串中获取名称“two”的值。
const url = require('node:url');
const MyUrl = new URL('https://www.qikepu.com?two=1&two=2&two=3');
console.log("URL: ", MyUrl.href);
const Params = new URLSearchParams('two=1&two=2&two=3');
console.log("Query string: " + Params);
console.log("Trying to get the value of the first key 'two'.....");
console.log("The value is: " + Params.get("two"));
输出
正如我们在输出中看到的,get() 方法返回第一次出现的值。
URL: https://www.qikepu.com/?two=1&two=2&two=3
Query string: two=1&two=2&two=3
Trying to get the value of the first key 'two'.....
The value is: 1
Query string: two=1&two=2&two=3
Trying to get the value of the first key 'two'.....
The value is: 1
例
如果查询字符串中不存在要搜索的名称,则 get() 方法返回 null。
在下面的示例中,我们尝试获取查询字符串中不存在的名称的值。
const url = require('node:url');
const MyUrl = new URL('https://www.qikepu.com?HTML=499&NODEJS=999&CSS=699');
console.log("URL: ", MyUrl.href);
const Params = new URLSearchParams('HTML=499&NODEJS=999&CSS=699');
console.log("Query string: " + Params);
console.log("Trying to get the value of the first key 'JavaScript'.....");
console.log("The value is: " + Params.get("JavaScript"));
输出
正如我们在输出中看到的,get() 方法返回 null。
URL: https://www.qikepu.com/?HTML=499&NODEJS=999&CSS=699
Query string: HTML=499&NODEJS=999&CSS=699
Trying to get the value of the first key 'JavaScript'.....
The value is: null
Query string: HTML=499&NODEJS=999&CSS=699
Trying to get the value of the first key 'JavaScript'.....
The value is: null