All files / location getQuery.js

94.74% Statements 18/19
58.33% Branches 7/12
100% Functions 2/2
94.74% Lines 18/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                1x     1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x       1x     1x     1x     1x  
/**
 * 解析 location.search 为一个JSON对象
 * - 或者获取其中某个参数
 * @method location/getQuery
 * @param {String} url URL字符串
 * @param {String} name 参数名称
 * @returns {Object|String} query对象 | 参数值
 * @example
 * var $getQuery = require('@spore-ui/kit/packages/location/getQuery');
 * var url = 'http://localhost/profile?beijing=huanyingni';
 * console.info( $getQuery(url) );
 * // {beijing : 'huanyingni'}
 * console.info( $getQuery(url, 'beijing') );
 * // 'huanyingni'
 */
 
var cache = {};
 
function getQuery(url, name) {
  var query = cache[url] || {};
 
  Eif (url) {
    var searchIndex = url.indexOf('?');
    Eif (searchIndex >= 0) {
      var search = url.slice(searchIndex + 1, url.length);
      search = search.replace(/#.*/, '');
 
      var params = search.split('&');
      params.forEach(function (group) {
        var equalIndex = group.indexOf('=');
        Eif (equalIndex > 0) {
          var key = group.slice(0, equalIndex);
          var value = group.slice(equalIndex + 1, group.length);
          query[key] = value;
        }
      });
    }
    cache[url] = query;
  }
 
  Iif (!name) {
    return query;
  }
  return query[name] || '';
}
 
module.exports = getQuery;