Updated URL parameters
This commit is contained in:
@ -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'}
|
||||
```
|
||||
|
||||
|
||||
@ -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'}
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user