all files / src/Url/ index.js

0% Statements 0/23
0% Branches 0/14
0% Functions 0/2
0% Lines 0/22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48                                                                                               
/**
* toQueryString url参数转对象
* @since 1.0.0
* @param {String} url default:window.location.href
* @returns {Object}
*/
export function toQueryString(url) {
  url = !url ? window.location.href : url;
  if(url.indexOf('?') === -1) {
    return {};
  }
  let search = url[0] === '?' ? url.substr(1) : url.substring(url.lastIndexOf('?') + 1);
  if (search === '') {
    return {};
  }
  search = search.split('&');
  let query = {};
  for (let i = 0; i < search.length; i++) {
    let pair = search[i].split('=');
    query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
  }
  return query;
}
 
/**
* stringify 对象序列化
* @since 1.0.0
* @param {Object} obj
* @returns {String}
*/
export function stringify(obj) {
  if (!obj) return '';
  let pairs = [];
  for (let key in obj) {
    let value = obj[key];
 
    if (value instanceof Array) {
      for (let i = 0; i < value.length; ++i) {
        pairs.push(encodeURIComponent(key + '[' + i + ']') + '=' + encodeURIComponent(value[i]));
      }
      continue;
    }
    pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
  }
 
  return pairs.join('&');
}