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 49 50 51 52 53 54 55 56 57 58 59 60 61 | 10x 10x 9x 9x 9x 9x 9x 10x 10x 6x 10x 9x 12x 12x 1x 11x 9x 9x 1x 8x 12x 9x 1x | /**
* 将参数设置到 location.search 上
* @method location/setQuery
* @param {String} url URL字符串
* @param {Object} query 参数对象
* @returns {String} 拼接好参数的URL字符串
* @example
* var $setQuery = require('@spore-ui/kit/packages/location/setQuery');
* $setQuery('localhost'); // 'localhost'
* $setQuery('localhost', {a: 1}); // 'localhost?a=1'
* $setQuery('', {a: 1}); // '?a=1'
* $setQuery('localhost?a=1', {a: 2}); // 'localhost?a=2'
* $setQuery('localhost?a=1', {a: ''}); // 'localhost?a='
* $setQuery('localhost?a=1', {a: null}); // 'localhost'
* $setQuery('localhost?a=1', {b: 2}); // 'localhost?a=1&b=2'
* $setQuery('localhost?a=1&b=1', {a: 2, b: 3}); // 'localhost?a=2&b=3'
* $setQuery('localhost#a=1', {a: 2, b: 3}); // 'localhost?a=2&b=3#a=1'
* $setQuery('#a=1', {a: 2, b: 3}); // '?a=2&b=3#a=1'
*/
function setQuery(url, query) {
url = url || '';
if (!query) { return url; }
var reg = /([^?#]*)(\?{0,1}[^?#]*)(#{0,1}.*)/;
return url.replace(reg, function (match, path, search, hash) {
search = search || '';
search = search.replace(/^\?/, '');
var para = search.split('&').reduce(function (obj, pair) {
var arr = pair.split('=');
if (arr[0]) {
obj[arr[0]] = arr[1];
}
return obj;
}, {});
Object.keys(query).forEach(function (key) {
var value = query[key];
if (value === null || typeof value === 'undefined') {
delete para[key];
} else {
para[key] = value;
}
});
var paraKeys = Object.keys(para);
if (!paraKeys.length) {
search = '';
} else {
search = '?' + paraKeys.map(function (key) {
return key + '=' + para[key];
}).join('&');
}
return path + search + hash;
});
}
module.exports = setQuery;
|