Updated URL parameters

This commit is contained in:
Angelos Chalaris
2017-12-13 14:09:25 +02:00
parent e9c534c395
commit 5522a4c207
2 changed files with 8 additions and 6 deletions

View File

@ -615,13 +615,14 @@ const unique = arr => [...new Set(arr)];
### URL parameters
Use `match()` with an appropriate regular expression to get all key-value pairs, `map()` them appropriately.
Combine all key-value pairs into a single object using `Object.assign()` and the spread operator (`...`).
Use `match()` with an appropriate regular expression to get all key-value pairs, `Array.reduce()` to map and combine them into a single object.
Pass `location.search` as the argument to apply to the current `url`.
```js
const getUrlParameters = url =>
Object.assign(...url.match(/([^?=&]+)(=([^&]*))?/g).map(m => {[f,v] = m.split('='); return {[f]:v}}));
url.match(/([^?=&]+)(=([^&]*))?/g).reduce(
(a,v) => (a[v.slice(0,v.indexOf('='))] = v.slice(v.indexOf('=')), a), {}
);
// getUrlParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}
```

View File

@ -1,11 +1,12 @@
### URL parameters
Use `match()` with an appropriate regular expression to get all key-value pairs, `map()` them appropriately.
Combine all key-value pairs into a single object using `Object.assign()` and the spread operator (`...`).
Use `match()` with an appropriate regular expression to get all key-value pairs, `Array.reduce()` to map and combine them into a single object.
Pass `location.search` as the argument to apply to the current `url`.
```js
const getUrlParameters = url =>
Object.assign(...url.match(/([^?=&]+)(=([^&]*))?/g).map(m => {[f,v] = m.split('='); return {[f]:v}}));
url.match(/([^?=&]+)(=([^&]*))?/g).reduce(
(a,v) => (a[v.slice(0,v.indexOf('='))] = v.slice(v.indexOf('=')), a), {}
);
// getUrlParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}
```