获取参数url解析
vue-router
if (this.$route.query.keywords) this.keywords = this.$route.query.keywords
if (this.$route.query.auth) this.auth = this.$route.query.auth
split方法截取
function getUrlParams(url) {
let queryString = url ? url.split('?')[1] : window.location.search.slice(1);
let obj = {}
if (!queryString) return obj
queryString = queryString.split('#')[0];
let arr = queryString.split("&")
for (let index = 0; index < arr.length; index++) {
const elementArr = arr[index].split("=");
obj[elementArr[0]] = elementArr[1]
}
return obj
}
console.log(getUrlParams('www.baidu.com?name=1111&key=000'))
方案优化
const getParameters = URL => JSON.parse(`{"${decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`
)
getParameters("https://www.google.com.hk/search?q=js+md&newwindow=1");
// {q: 'js+md', newwindow: '1'}
11:00:25.454
URLSearchParams
// URL is http://NaoNao.com/?product=shirt&color=blue&newuser&size=m
const urlParams = new URLSearchParams(window.location.search);
// 判断参数是否存在
console.log(urlParams.has('product')); // true
// 获取参数对应的值
console.log(urlParams.get('product')); // "shirt"
node模块-querystring
function transUrl(url) {
if (!url) return url
const querystring = require('querystring');
return querystring.parse(url)
}
//const querystring = require('querystring');
import querystring from "querystring"
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
// 返回 'foo=bar&baz=qux&baz=quux&corge='