-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathhandleHash.js
73 lines (66 loc) · 1.6 KB
/
handleHash.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const defaultPrependHash = '#/';
const separator = '/';
const hashValRegexp = /(.*)\?/;
function escapeRegExp(str) {
return String(str || '').replace(/\W/g, '\\$&');
}
function trimHash(hash, prependHash) {
if (!hash) {
return '';
}
const regexp = new RegExp('^' + escapeRegExp(prependHash || defaultPrependHash), 'g');
return hash.replace(regexp, '');
}
const trimParams = hash => {
const result = hashValRegexp.exec(hash);
return (result && result[1]) || hash;
};
/**
* If hash has a certain element
*
* @param {string} hash
* @param {string} search
* @return {boolean}
*/
export const hasInHash = (hash, search) => {
return hash !== '' && hash.indexOf(search) > -1;
};
/**
* Get hash value without '#', prependHash and parameters
*
* @param {string} hash
* @param {string} prependHash
* @return {string}
*/
export const getHash = (hash, prependHash) => {
return decodeURIComponent(trimParams(trimHash(hash, prependHash)));
};
/**
* Get hash value split into an Array.
*
* @param {string} hash
* @param {string} prependHash
* @return {Array.<string>}
*/
export const getHashAsArray = (hash, prependHash) => {
return getHash(hash, prependHash).split(separator);
};
/**
* Get a parameter by name in hash
*
* @param {string} hash
* @param {string} name
* @return {string}
*/
export const getParameterByName = (hash, name) => {
name = name.replace(/[[\]]/g, '\\$&');
const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
const results = regex.exec(hash);
if (!results) {
return null;
}
if (!results[2]) {
return '';
}
return decodeURIComponent(results[2].replace(/\+/g, ' '));
};