-
Notifications
You must be signed in to change notification settings - Fork 0
/
query-params-utils.js
57 lines (50 loc) · 1.94 KB
/
query-params-utils.js
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
define(
'query-params-utils',
function () {
'use strict';
/**
* Add / Update a map of URL query parameters.
* Handles Hash.
*
* @param {String} url The initial URL. The parameter won't be modified.
* @param {Array} params [{"key":"myKey", ""value":"myValue"}]
*
* @return String modified URL
*/
function putUrlParameters(url, params) {
var modifiedUrl = url;
for (var i = 0; i < params.length; i++) {
modifiedUrl = putUrlParameter(modifiedUrl, params[i].key, params[i].value);
}
return modifiedUrl;
}
/**
* Add / Update a query parameter.
* Handles Hash.
*
* @param {String} url The initial URL. The parameter won't be modified.
* @param {String} key The key of the query param. ! No encoding will be applied on it.
* @param {String} value The value of the query param. ! No encoding will be applied on it.
*
* @return String modified URL
*/
function putUrlParameter(url, key, value) {
var modifiedUrl = url;
var i = modifiedUrl.indexOf('#');
var hash = i === -1 ? '' : modifiedUrl.substr(i);
modifiedUrl = i === -1 ? modifiedUrl : modifiedUrl.substr(0, i);
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = modifiedUrl.indexOf('?') !== -1 ? "&" : "?";
if (modifiedUrl.match(re)) {
modifiedUrl = modifiedUrl.replace(re, '$1' + key + "=" + value + '$2');
} else {
modifiedUrl = modifiedUrl + separator + key + "=" + value;
}
modifiedUrl += hash;
return modifiedUrl;
}
return {
putUrlParameters:putUrlParameters,
putUrlParameter:putUrlParameter
}
});