Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

第 79 期(W3C 标准-URL):URLSearchParams #82

Copy link
Copy link
@wingmeng

Description

@wingmeng
Issue body actions

本期要介绍的是一个非常实用的 API —— URLSearchParams

从字面意思来看,这个 API 应该是用来处理 URL 的查询字符串的,事实上,它不仅可以轻松摆平 URL 查询字符串,而且还提供了许多非常丝滑的处理方法供开发者使用。
在此之前要对 URL 传参进行相关操作是比较繁琐的,常见的方法是通过前后两次 split 划分字符串为数组,找出参数,或者通过正则表达式匹配出参数。这类方法写起来成本较高,而且对于一些比较特殊的 URL 参数很容易出错(例如下面这些)。

http://xx.xx.xx?from=user.html?id=1
http://xx.xx.xx?favorite=rap&favorite=basketball&favorite=music

用法:

let urlParams = '?action=edit&username=Kitty&from=?user-list.html&favorite=rap&favorite=music&favorite=reading';

// 创建实例
let params = new URLSearchParams(urlParams);

console.log('是否有 action 字段:', params.has('action'));  // true
console.log('获取 username:', params.get('username'));  // Kitty
console.log('获取 from:', params.get('from'));  // ?user-list.html
console.log('获取 favorite:', params.get('favorite'));  // rap
console.log('获取全部 favorite:', params.getAll('favorite'));  //  ["rap", "music", "reading"]
console.log('输出所有的 key:', [...params.keys()]);
console.log('输出所有的 values:', [...params.values()]);
params.append('area', 'China');  // 追加数据
console.log('输出为字符串形式:', params.toString());

实例方法:

方法 描述
append() 向 URL 中追加数据(key/value)
delete() 删除所有匹配的 key/value 值
entries() 返回所有键值对 key/value
get() 返回与给定 key 匹配的第一个 value 值
getAll() 返回所有与给定 key 匹配 value 值
has() 查询指定 key 是否存在,返回一个布尔值
keys() 返回所有键 key
set() 设置 key 的 value 值
toString() 返回 URL 字符串
values() 返回所有值

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.