Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing URL string with lodash

How can I parse URL string using only lodash functions without any callbacks inside?

Ex.

var rawUrl = “?a=b454&c=dhjjh&f=g6hksdfjlksd..”

My current solution is

var answer = _.reduce(_.split(_.replace(rawUrl,'?',''), '&'), function(result, ev) {
    (result[ev.split('=')[0]] || (result[ev.split('=')[0]] = [])).push(ev.split('=')[1]);
    return result;
}, {});

But still, one callback is present here.

like image 712
Myroslava Kozachuk Avatar asked Dec 23 '16 09:12

Myroslava Kozachuk


3 Answers

I'm aware that you asked for a lodash solution, but maybe people who read the question might also want to look at URLSearchParams, it helped me using less code than the ES6 approach, and avoiding lodash.

const params = new URLSearchParams(window.location.search);

to access a query parameter called 'a'

let a = params.get('a');

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

like image 63
chriszichrisz Avatar answered Oct 18 '22 22:10

chriszichrisz


to avoid callback use _.partial, _.partialRight and other lodash methods to work with functions

_.chain(rawUrl)
    .replace('?', '') // a=b454&c=dhjjh&f=g6hksdfjlksd
    .split('&') // ["a=b454","c=dhjjh","f=g6hksdfjlksd"]
    .map(_.partial(_.split, _, '=', 2)) // [["a","b454"],["c","dhjjh"],["f","g6hksdfjlksd"]]
    .fromPairs() // {"a":"b454","c":"dhjjh","f":"g6hksdfjlksd"}
    .value()
like image 43
stasovlas Avatar answered Oct 19 '22 00:10

stasovlas


Es6 way without lodash :

  const urlParsed =
    rawUrl.substring(rawUrl.indexOf("?") + 1)
          .split("&")
          .reduce(
            (memo, param) => ({
              ...memo,
              [param.split("=")[0]]: param.split("=")[1]
            }),
            {}
          );
like image 3
regisg Avatar answered Oct 19 '22 00:10

regisg