关于javascript:前端实用小工具三去空格JOSN转url参数删除url参数等

35次阅读

共计 1485 个字符,预计需要花费 4 分钟才能阅读完成。

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';}
}

删除 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;}
}

获取 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;
}

去除字符串空格

/**
 * @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;
    }
}

正文完
 0