码迷,mamicode.com
首页 > Web开发 > 详细

URL 参数解析

时间:2019-10-04 20:41:41      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:parameter   cat   delete   ons   new   amp   value   query   href   

  1. url参数解析为对象
  2. url参数解析为数组
  3. URLSearchParams(兼容性有待提高,慎用)

url参数解析为对象

const urlQueryToObject = (url) => {
    if((/\?/).test(url)) {
        const arr =  url.split('?')[1].split('&');

        return  arr.reduce((acc,value,index) => {value.replace(/(\w+)=(\w+)/,(match,p1,p2) => {acc[p1] = p2});return acc},{});
    }
    return {}
}

const getURLParameters = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
    {}
);
// example
// location.href ='http://example.com/user?id=1&age=2'
const paramsObj = urlQueryToObject(location.href)  //{id: "1", age: "2"}
paramsObj.id 
paramsObj.age

url参数解析为数组

const urlQueryToArr = url => {
    if((/\?/).test(url)) {
        const arr = url.split('?')[1].split('&');
        return arr.reduce((acc,value,index) => {acc.push(value.split('='));return acc;},[])
    }
    return []
}
// example
// location.href ='http://example.com/user?id=1&age=2' 
JSON.stringify(urlQueryToArr(location.href)) //  "[["id","1"],["age","2"]]"

URLSearchParams

/**
 * 
 * @param {string} url 
 * @return URLSearchParams ;
 */
const urlParams = url => {
    if(/\?/.test(url)) {
        return searchParams = new URLSearchParams( url.split('?')[1]);
    }
    return new URLSearchParams()
}

useage

// location.href ='http://example.com/user?id=1&age=2' 
const params = urlParams(location.href);  //iterater obj
params.get('id') // 1
params.has('id') // true
params.append('id','2')
params.getAll('id')  //  ?["1", "2"]
params.set('id','0') 
params.get('id') //  "0"
params.getAll('id') //  ["0"]
params.delete('id')
params.get('id')  // null
params.toString() //"age=2"

references:

URL 参数解析

标签:parameter   cat   delete   ons   new   amp   value   query   href   

原文地址:https://www.cnblogs.com/rosendolu/p/11623065.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!