0

I have given an url

const url = 'http://localhost:3000/?user=123&LEA_CODE=123&RES_PHONE=+77055321767&token=asd'

I need to parse it into object. I tried creating an array using split

url.split('/')[url.split('/').length-1].split('&')

What I got is array

["?user=123", "LEA_CODE=123", "RES_PHONE=+455566", "token=asd"]

How do I transform this array into object

{
user: 123,
LEA_CODE= 123,
RES_PHONE: +455566,
token: asd
}

I think I should use reduce method. But I don't know how

Andreas
  • 21,535
  • 7
  • 47
  • 56
hideo
  • 11
  • 4
  • An array is an object. However you want keys. Why not try `Object.fromEntries(urlArray.map(part => part.split("=")))`? – evolutionxbox Jun 24 '21 at 09:36
  • Although you might want to remove the leading `?` before manipulating the string. – evolutionxbox Jun 24 '21 at 09:36
  • 2
    If you just want the URL parameters, then use [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams). If you want to parse the whole URL, then [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL). Don't reinvent the wheel. – VLAZ Jun 24 '21 at 09:37
  • yes, I also want to delete '?' – hideo Jun 24 '21 at 09:38

0 Answers0