小记--获取url键值

369 阅读1分钟

以后会不定期把项目中用到的也是我们平时开发常用的一些方法贴出来,也是一个自我总结的过程

获取url键值是我们在项目会经常遇到的需求。下面是我在项目中封装的方法,详细的说明在代码都有注释。点这里

/**
 * 获取url键值
 * url => [href] | [param]
 * 不填参数则返回JSON 格式所有数据
 */
const urlCodeToObj = url => {
    let u = url || window.location.href
    //判断url是完整的链接还是传入的参数
    if (RegExp(/^((https|http)?:\/\/)/).test(u)) {
    //将url中的空格去掉并匹配'?'后面的参数字符串集合
    	const search = u.replace(/^\s+|\s+$/, '').match(/([^?#]*)(#.*)?$/)
    	if (!search) {
    		search = {}
    	}
    	//把匹配到的字符串以'&'分割变换成数组形式
    	let searchHash = search[1].split('&');
    	let paramObj = {} //键值对对象集合
    	for (let item of searchHash) {
            const pair = item.split('=')
            if (pair[0]) {
            	const key = decodeURIComponent(pair[0])
            	const value = pair[1]
            	if (value != undefined) {
	            value = decodeURIComponent(value)
            	}
            }
            //判断转化后的paramObj里面有没有重复的属性
            if (key in paramObj) {
            	if (paramObj[key] instanceof Array) {
                    //把属性值变为数组,将另外的属性值也存放到数组中去
                    paramObj[key] = [paramObj[key]]
            	}
            	paramObj[key].push(value)
            } else {
            	paramObj[key] = value
            }
    	}
    	return paramObj
    } else {
    	//返回单个属性值 string
    	if (RegExp(/^\w+/).test(u)) {
            //匹配属性值,比如http://xxx.com/web/page/prodetail.html?num=200&productID=4690&id=100
            //输入值为 &productID=4690&,然后进行匹配.
            let reg = new RegExp(`(^|&)${u}=([^&]*)(&|$)`,"i")
            const matchArr = window.location.search.substr(1).match(reg)
            if (matchArr != null) return (matchArr[2])
            return null
    	}
    }
}