From e5635a402cbb3171a7fa97e4e0f96f8f182c487f Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Wed, 13 Dec 2017 14:09:25 +0200 Subject: [PATCH] Updated URL parameters --- README.md | 7 ++++--- snippets/URL-parameters.md | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 7f583154b..c6bcb3855 100644 --- a/README.md +++ b/README.md @@ -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'} ``` diff --git a/snippets/URL-parameters.md b/snippets/URL-parameters.md index 4620513dc..42a43cc22 100644 --- a/snippets/URL-parameters.md +++ b/snippets/URL-parameters.md @@ -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'} ```