nyawach
11/16/2018 - 2:17 AM

クエリをパース/文字列化するやつ

クエリをパース/文字列化するやつ

class QueryString {

  parse(search) {
    let obj = {}
    search = search.replace(/^\?/, "")
    const pairs = search.split("&")
    pairs.forEach(pair => {
      const [key, val] = pair.split("=")
      obj[key] = val
    })
    return obj
  }

  stringify(obj = {}, { question = false } = {}) {
    let str = ""
    let keys = Object.keys(obj)
    keys.forEach((key, i) => {
      if(i > 0) str += "&"
      else if(question) str += "?"
      str += `${key}=${obj[key]}`
      return str
    })
    return str
  }
}