20

JSON转URL参数

export function paramsToUrlQuery(params) {
    let types = Object.prototype.toString.call(params).slice(8, -1);
    if (types === 'Object') {
        let tempArr = [];
        for (let i in params) {
            let key = encodeURIComponent(i);
            let value = encodeURIComponent(params[i]);
            tempArr.push(key + '=' + value);
        }
        let urlParamsStr = tempArr.join('&');
        return urlParamsStr;
    } else {
        throw 'model is not object';
    }
}

image-20201021110205911

删除url指定参数

export function delUrlParam(url, key) {
    let baseUrl = url.split('?')[0] + '?';
    let query = url.split('?')[1];
    if (query.indexOf(key) > -1) {
        let obj = {};
        let arr = query.split('&');
        for (let i = 0; i < arr.length; i++) {
            arr[i] = arr[i].split('=');
            obj[arr[i][0]] = arr[i][1];
        }
        delete obj[key];
        let url =
            baseUrl +
            JSON.stringify(obj)
                .replace(/[\"\{\}]/g, '')
                .replace(/\:/g, '=')
                .replace(/\,/g, '&');
        return url;
    } else {
        return url;
    }
}

image-20201021154629569

获取url全部参数转json

export function getAllUrlParamsToJson (url) {
  let urlRes = url ? url : window.location.href;
  let _pa = urlRes.substring(urlRes.indexOf('?') + 1),
      _arrS = _pa.split('&'),
      _rs = {};
  for (let i = 0, _len = _arrS.length; i < _len; i++) {
      let pos = _arrS[i].indexOf('=');
      if (pos == -1) {
          continue;
      }
      let name = _arrS[i].substring(0, pos),
          value = window.decodeURIComponent(_arrS[i].substring(pos + 1));
      _rs[name] = value;
  }
  return _rs;
}

image-20201021160959984

去除字符串空格

/**
 * @description 去除空格
 * @param { string } str 待处理字符串
 * @param  { number } type 去除空格类型 1-所有空格  2-前后空格  3-前空格 4-后空格 默认为1
 */
export function trim(str, type = 1) {
    if (type && type !== 1 && type !== 2 && type !== 3 && type !== 4) return;
    switch (type) {
        case 1:
            return str.replace(/\s/g, '');
        case 2:
            return str.replace(/(^\s)|(\s*$)/g, '');
        case 3:
            return str.replace(/(^\s)/g, '');
        case 4:
            return str.replace(/(\s$)/g, '');
        default:
            return str;
    }
}

image-20201021140442396


兰俊秋雨
5.1k 声望3.5k 粉丝

基于大前端端技术的一些探索反思总结及讨论