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

4
  • An array is an object. However you want keys. Why not try Object.fromEntries(urlArray.map(part => part.split("=")))? Commented Jun 24, 2021 at 9:36
  • Although you might want to remove the leading ? before manipulating the string. Commented Jun 24, 2021 at 9:36
  • 2
    If you just want the URL parameters, then use URLSearchParams. If you want to parse the whole URL, then URL. Don't reinvent the wheel. Commented Jun 24, 2021 at 9:37
  • yes, I also want to delete '?' Commented Jun 24, 2021 at 9:38

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.