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

解析url中的queryString #11

Open
yijinc opened this issue Aug 20, 2021 · 1 comment
Open

解析url中的queryString #11

yijinc opened this issue Aug 20, 2021 · 1 comment
Labels
coding test or practice

Comments

@yijinc
Copy link
Owner

yijinc commented Aug 20, 2021

解析url中的queryString

入参格式参考:

const url = "https://www.youzan.com?name=coder&age=20&callback=https%3A%2F%2Fyouzan.com%3Fname%3Dtest&list[]=a&list[]=b&json=%7B%22str%22%3A%22abc%22,%22num%22%3A123%7D"

出参格式参考:

{
  name: "coder",
  age: "20",
  callback: "https://youzan.com?name=test",
  list: ["a", "b"],
  json: {
    str: 'abc',
    num: 123
  }
}
@yijinc yijinc changed the title 【Coding】:解析url中的queryString Coding:解析url中的queryString Aug 20, 2021
@yijinc yijinc added the coding test or practice label Aug 20, 2021
@yijinc
Copy link
Owner Author

yijinc commented Aug 20, 2021

参考方法1
function parseQuery(url) {
    const obj = {}
    const searchParams = new URLSearchParams(new URL(url).search)
    for (let [key, value] of searchParams.entries()) {
        if (value.startsWith('{')) {
            value = JSON.parse(value)
        }
        if(!obj[key]) {
            obj[key] = value
        } else {
            // 如果存在多个值,把第一个存到数组
            if (!Array.isArray(obj[key])) {
                obj[key] = [obj[key]]
            }
            obj[key].push(value)
        }
    }
    return obj
}

@yijinc yijinc changed the title Coding:解析url中的queryString 解析url中的queryString Jun 30, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
coding test or practice
Projects
None yet
Development

No branches or pull requests

1 participant