获取参数url解析

vue-router

  1. if (this.$route.query.keywords) this.keywords = this.$route.query.keywords
  2. if (this.$route.query.auth) this.auth = this.$route.query.auth

split方法截取

  1. function getUrlParams(url) {
  2. let queryString = url ? url.split('?')[1] : window.location.search.slice(1);
  3. let obj = {}
  4. if (!queryString) return obj
  5. queryString = queryString.split('#')[0];
  6. let arr = queryString.split("&")
  7. for (let index = 0; index < arr.length; index++) {
  8. const elementArr = arr[index].split("=");
  9. obj[elementArr[0]] = elementArr[1]
  10. }
  11. return obj
  12. }
  13. console.log(getUrlParams('www.baidu.com?name=1111&key=000'))

方案优化

  1. const getParameters = URL => JSON.parse(`{"${decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`
  2. )
  3. getParameters("https://www.google.com.hk/search?q=js+md&newwindow=1");
  4. // {q: 'js+md', newwindow: '1'}
  5. 11:00:25.454

URLSearchParams

  1. // URL is http://NaoNao.com/?product=shirt&color=blue&newuser&size=m
  2. const urlParams = new URLSearchParams(window.location.search);
  3. // 判断参数是否存在
  4. console.log(urlParams.has('product')); // true
  5. // 获取参数对应的值
  6. console.log(urlParams.get('product')); // "shirt"

node模块-querystring

  1. function transUrl(url) {
  2. if (!url) return url
  3. const querystring = require('querystring');
  4. return querystring.parse(url)
  5. }
  1. //const querystring = require('querystring');
  2. import querystring from "querystring"
  3. querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
  4. // 返回 'foo=bar&baz=qux&baz=quux&corge='