5

I fail to parse the first query string parameter using the qs npm package. What am I doing wrong?

I execute these commands in my console

import * as qs from './qs'
var addr = "https://www.somesite.se/?title=querystring&action=edit"
var parsed = qs.parse(addr)

After executing these commands parsed has the value:

{ 'https://www.somesite.se/?title': 'querystring',
  action: 'edit' }

This is strange. Why is title not a property on the returned object? I would expect the value of parsed.title to be 'querystring'. but it is not. The value of parsed.title is undefined.

Why?

user1283776
  • 19,640
  • 49
  • 136
  • 276
  • Related: [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Ram Sep 27 '18 at 11:58

2 Answers2

9

qs parses query strings. It does not parse URLs. Use a URL parser (new URL(addr).search.substring(1)) to get the query string from the URL first.

qs.parse("title=querystring&action=edit") should give you a correct answer.

Now that I think about it... why even use qs? new URL(addr).searchParams should already give you the params parsed...

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • I got really excited about using searchParams, but unfortunately those appear to only be available in web workers: https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams – Lokua Jan 14 '21 at 19:04
  • 1
    @Lokua The page says it is available in Web Workers. It is not _only_ available in Web Workers. It is in Node, it is in regular JS, and _also_ in Web Workers. Try in all of those environments: `new URL("https://www.somesite.se/?title=querystring&action=edit").searchParams.get('action')` (except in weird browsers like IE). – Amadan Jan 14 '21 at 22:55
  • Thank you @Amadan! I did not realize it was a map when I logged `new URL(...).searchParams` in the console it just looked like an empty object but expanding it I see it's a Map-like class. – Lokua Jan 16 '21 at 04:55
7

The answer is: the qs library is using for parsing the query string only.

According to Wikipedia:

a query string is the part of a uniform resource locator (URL) which assigns values to specified parameters.

For example:

enter image description here

In your case, the correct codes should be:

var addr = 'title=querystring&action=edit';
var parsed = qs.parse(addr);
console.log(parsed); // {title: "querystring", action: "edit"}

To bypass the leading question mark, use ignoreQueryPrefix:

var addr2 = '?title=querystring&action=edit';
var parsed2 = qs.parse(addr2, { ignoreQueryPrefix: true });
console.log(parsed2); // {title: "querystring", action: "edit"}

Hopefully, that helps!

You Nguyen
  • 9,961
  • 4
  • 26
  • 52