There are few existing libraries for that - npm state-in-url, npm NUQS, those made good enough and maintained.
npm state-in-url
npm NUQS
It's educational to implement it from scratch, but there are enough hidden pitfalls.