Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

96.URL解析 #96

Open
neptoo opened this issue Dec 5, 2019 · 0 comments
Open

96.URL解析 #96

neptoo opened this issue Dec 5, 2019 · 0 comments

Comments

@neptoo
Copy link
Owner

neptoo commented Dec 5, 2019

URL解析

脚本

const url = new URL('http://www.pushme.top/users?sort_by=asc#page=userlist')
console.log(url)

解析

{
    hash: "#page=userlist"
    host: "www.pushme.top"
    hostname: "www.pushme.top"
    href: "http://www.pushme.top/users?sort_by=asc#page=userlist"
    origin: "http://www.pushme.top"
    password: ""
    pathname: "/users"
    port: ""
    protocol: "http:"
    search: "?sort_by=asc"
    searchParams: URLSearchParams {}
    username: ""
}

获取URL的query

?search=aquery 以第一个?开始至行尾#结束。用于向后端传递一些数据,数据使用 & 进行分隔,值使用 = 分隔。通过一段代码来理解一下:

const query = 'id=1&sort=asc&hello=world';
// 对 & 分割取得数据对
const data = query.split('&').reduce((data,keyValue) => {
    const [ key, value ] = keyValue.split('=');
    return (data[key] = value, data);
}, {});

// 输出 {id: "1", sort: "asc", hello: "world"}
console.log(data);

URLSearchParams

let url = '?name=neptoo&skill=fed&year=2019';
let searchParams = new URLSearchParams(url);

for (let p of searchParams) {
  console.log(p);
}
// ["name", "neptoo"]
// ["skill", "fed"]
// ["year", "2019"]

获取单个字段

searchParams.get('year') // "2019"

校验字段是否存在

searchParams.has('skill') // true

添加字段

实例提供了append方法来添加字段,这个方法接收两个参数,前者是key,后者是value:

searchParams.append('age', 26);

删除字段

searchParams.delete('year');

重写字段

searchParams.set('skill', 'vue react vite webpack');

阅读原文

前端必知必会--操作URL的黑科技

每日 30 秒 ⏱ URL 大爆炸

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant