qs.parse read query param without decoding

Viewed 305

I am trying to get email from URL without decoding.

URL: https://localhost:3000/register/activate?token=JAItBAPArUSukXae0Q3J&email=kiran+39@gmail.com

Note: Due to some technical limitation I can not encode the URL. Since it's coming from a third party vendor.

Initial code:

var email = qs.parse(window.location.search, {
    ignoreQueryPrefix: true,
  }).email;

This works but when email has "+" sign it decodes it as " ". So, I am trying to replace spaces with "+" again with the below code. But I am having some issue with types. Can you please help me what's the best way to fix this.

Code:

  let email: string =
    qs.parse(window.location.search, {
      ignoreQueryPrefix: true,
    }).email || "";

  if (email) email.replace(/ /g, "+");

enter image description here

But I am getting a type error:

Argument of type 'string | string[] | ParsedQs | ParsedQs[] | undefined' is not assignable to parameter of type 'string'

1 Answers

The work-around for this is to pass a custom decoder to qs.parse, one that simply returns the string without decoding it

const email = qs.parse(search, {
  ignoreQueryPrefix: true,
  decoder: s => s
}).email

Edit dreamy-thunder-uwi9n

Related