URLSearchParams 接口

URLSearchParams 接口指定用于处理 URL 查询字符串的实用方法。
URLSearchParams 建议对 URL 的各个部分使用一致的接口,并允许对查询字符串(“?”之后的内容)进行操作。

使用JavaScript如何获取 URL 的参数

URL 参数或者查询字符串参数用于通过 URL 从客户端向服务器发送一条数据。
它们可以包含诸如搜索查询、链接推荐、用户偏好等信息。

URLSearchParams 接口可以更容易地获取 URL 的参数。
它提供了处理 URL 查询字符串的方法。

让我们通过 window.location.search 获取“https://example.com/?product=troussers&color=black&newuser&size=s” URL 的查询字符串:

const queryString = window.location.search;
console.log(queryString);
//?product=troussers&color=black&newuser&size=s

要解析查询字符串的参数,请使用 URLSearchParams:

const urlParams = new URLSearchParams(queryString);

URLSearchParams.get() 方法返回与给定搜索参数关联的第一个值:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
  </head>
  <body>
    <script>
      const urlParams = new URLSearchParams("https://example.com/?product=troussers&color=black&newuser&size=s");
      const size = urlParams.get('size');
      alert(size);
      //s
      const color = urlParams.get('color')
      alert(color);
      //black      
      const newUser = urlParams.get('newuser')
      alert(newUser);
      //empty string
    </script>
  </body>
</html>

如果要检查给定参数是否存在,请使用: URLSearchParams.has():

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
  </head>
  <body>
    <script>
      const urlParams = new URLSearchParams("https://example.com/?product=troussers&color=black&newuser&size=s");
      alert(urlParams.has('size'));
      //true
      alert(urlParams.has('paymentmethod'));
      //false
    </script>
  </body>
</html>

URLSearchParams.getAll() 方法返回与某个参数关联的所有值:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
  </head>
  <body>
    <script>
      const urlParams = new URLSearchParams("https://example.com/?product=troussers&color=black&newuser&size=s");
      alert(urlParams.getAll('color'));
      //[ 'black' ]
      //Programmatically add a second color parameter.
      urlParams.append('color', 'pink');
      alert(urlParams.getAll('color'));
      //[ 'black', 'pink' ]
    </script>
  </body>
</html>
日期:2020-06-02 22:16:21 来源:oir作者:oir