0

i have a scenario where i will get input as path and query param and in the place of value i will get a regex.

regex input contains & which is a delimiter in query param.

`Input :` '/austin/query.html?dept=([^&]*)&group=([^&]*)'

i want to get this regex ([^&]*) from query param dynamically.

Any idea or suggestions might be silly / basic question please do help ?

Vishnu Ranganathan
  • 1,277
  • 21
  • 45
  • 1
    What specific problem are you having? It should be URL-encoded in the URL. – Dave Newton May 26 '18 at 12:10
  • @DaveNewton : when i try to split using '&' iam getting output like this { dept: '([^', ']*)': [ '', '' ], group: '([^' } since & is a delimiter. i am expecting output like this [([^&]*),([^&]*)] picking the 2 regex from the input – Vishnu Ranganathan May 26 '18 at 12:14
  • 1
    @DaveNewton means that the input should be URL-encoded. So, the input should actually be: `/austin/query.html?dept=([^%26]*)&group=([^%26]*)`. This would make parsing much simpler on the server. – thgaskell May 26 '18 at 12:22
  • Thanks thgaskell and DaveNewton . perfect way to fix. Thanks a lot – Vishnu Ranganathan May 26 '18 at 12:27
  • Why would you split at all? Use a url processor. – Dave Newton May 26 '18 at 12:47
  • 1
    @Dave Can you give me more details i am currently using url module in node js. do recommend if there is any other better way to do . – Vishnu Ranganathan May 26 '18 at 12:54

1 Answers1

2

It's important to URL encode query parameters before the request is sent. This helps to avoid issues with characters that have special meaning (?, =, &, #, etc.)

So instead of sending literal ampersand characters & in the regex, it should be URL-encoded to be %26 instead.

/austin/query.html?dept=([^%26]*)&group=([^%26]*)

When this parsed by the querystring module, it will automatically be converted back to the ampersand character.

const querystring = require('querystring');
const URL = require('url');

function parseQueryParamsFromUrlPath(urlPath) {
  const { query } = URL.parse(urlPath);
  return querystring.parse(query);
}

parseQueryParamsFromUrlPath('/austin/query.html?dept=([^%26]*)&group=([^%26]*)');
// Output: { dept: '([^&]*)', group: '([^&]*)' }
thgaskell
  • 12,772
  • 5
  • 32
  • 38