将对象添加到URL中作为参数

  1. const params2Url = (uri, params) => {
  2. const paramsArray = [];
  3. Object.keys(params).forEach(
  4. (key) => params[key] && paramsArray.push(`${key}=${params[key]}`)
  5. );
  6. if (uri.search(/\?/) === -1) {
  7. uri += `?${paramsArray.join("&")}`;
  8. } else {
  9. uri += `&${paramsArray.join("&")}`;
  10. }
  11. return uri;
  12. };
  13. let params = {
  14. keyword: "t",
  15. page: 1,
  16. size: 2,
  17. };
  18. params2Url('/datasource/check/p', params)

提取出url 里的参数并转成对象

  1. function getUrlParams(url){
  2. let reg = /([^?&=]+)=([^?&=]+)/g
  3. let obj = { }
  4. url.replace(reg, function(){
  5. obj[arguments[1]] = arguments[2]
  6. })
  7. // 或者
  8. const search = window.location.search
  9. search.replace(/([^&=?]+)=([^&]+)/g, (m, $1, $2)=>{obj[$1] = decodeURIComponent($2)})
  10. return obj
  11. }
  12. let url = 'https://www.junjin.cn?a=1&b=2'
  13. console.log(getUrlParams(url)) // { a: 1, b: 2 }