在实际业务中, 需要对一长串的url进行解析,比如读取、添加或修改url中的queryString。

1. 获取url中的参数

/**
 * 获取url内query string的值
 * @param {String} url 网址
 * @param {String} paramName queryString name
 */
 function getUrlParamByName(url, paramName) {
  paramName = paramName.replace(/[\[\]]/g, '\\$&');
  let regular = new RegExp('[?&]' + paramName + '(=([^&#]*)|&|#|$)');
  let val = regular.exec(url);
  if (!val) {
    return null;
  }
  if (!val[2]) {
    return '';
  }
  return decodeURIComponent(val[2].replace(/\+/g, ' '));
}

示例:

let url = 'http://wwww.baidu.com/search?userId=6453705&token=b1d710d376498dd803e4e7a01e5932ef';

// 获取token
let token = getUrlParamByName(url, 'token');
console.log(token); // => b1d710d376498dd803e4e7a01e5932ef

  

2. 设置url中的参数

 说明:若当前url不存在此queryString,则进行追加操作。

/**
 * 设置url内query string的值
 * @param {String} url 网址
 * @param {String} paramName queryString name
 * @param {String} paramValue queryString value
 */
function setUrlParam(url, paramName, paramValue) {
  paramName = paramName.replace(/[\[\]]/g, '\\$&');
  let regular = new RegExp('[?&]' + paramName + '(=([^&#]*)|&|#|$)');
  let val = regular.exec(url);
  if (val && val[2]) {
    url = url.replace(new RegExp(paramName + '=' + val[2]), `${paramName}=${paramValue}`);
  } else {
    url += `&${paramName}=${paramValue}`;
  }

  return url;
}

示例:

let url = 'http://wwww.baidu.com/search?userId=6453705&token=b1d710d376498dd803e4e7a01e5932ef';

// 设置token
let newUrl = setUrlParam(url, 'token', '123');
console.log(newUrl); // => http://wwww.baidu.com/search?userId=6453705&token=123

// 若不存在queryString,进行追加操作
newUrl = setUrlParam(url, 'dt', Date.now());
console.log(newUrl); // => http://wwww.baidu.com/search?userId=6453705&token=b1d710d376498dd803e4e7a01e5932ef&dt=1669009911762

 

3. 清除url内指定的参数

说明:用于清除url中指定的queryString。

/**
 * 清除url内指定的param
 * @param {String} url 网址
 * @param {Array | String} paramNameList queryString name array
 */
function clearUrlParam(url, paramNameList) {
  if (!Array.isArray(paramNameList)) {
    paramNameList = [].concat(paramNameList);
  }

  paramNameList.forEach((paramName) => {
    paramName = paramName.replace(/[\[\]]/g, '\\$&');
    let regular = new RegExp('[?&]' + paramName + '(=([^&#]*)|&|#|$)');
    let val = regular.exec(url);
    if (val && val[2]) {
      url = url.replace(new RegExp('&?' + paramName + '=' + val[2]), '');
    }
  });

  if (url.endsWith('?')) {
    url = url.substring(0, url.length - 1);
  }

  return url;
}

示例:

let url = 'http://wwww.baidu.com/search?userId=6453705&token=b1d710d376498dd803e4e7a01e5932ef';

// 清除token
let newUrl = clearUrlParam(url, 'token');
console.log(newUrl); // => http://wwww.baidu.com/search?userId=6453705

// 清除多个
newUrl = clearUrlParam(url, ['userId', 'token']);
console.log(newUrl); // => http://wwww.baidu.com/search

 

 

 

posted on 2022-12-04 15:05  FangMu  阅读(25)  评论(0编辑  收藏  举报