0

I've been working on a parser for url queries but I'm stumped on why the regex is incorrect when it worked during test via regex101.com or atleast I think it did, it's been a late night coding;

Anyway I haven't found any answers searching both StackOverflow or Good Ol'e google.

Issue: UnhandledPromiseRejectionWarning: SyntaxError: Invalid regular expression: /\?(?<query>.*)/: Invalid group

   const results = url.match(/\?(?<query>.*)/);
    if (!results) {
        return {};
    }
    const { groups: { query } } = results;

    const pairs = query.match(/(?<param>\w+)=(?<value>\w+)/g);
    const params = pairs.reduce((acc, curr) => {
        const [key, value] = curr.split(("="));
        acc[key] = value;
        return acc;
    }, {});
    return params;
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Johnty
  • 246
  • 1
  • 2
  • 18
  • Is Node JS not ecmascript ? I thought JS was controlled by browsers. –  Oct 20 '20 at 00:20
  • @Maxt8r JS can run on many platforms. It's true that it's most widely seen on client's browsers, but it can also run on a server on the backend (with Node.js), or on desktop applications (with Electron), and more. – CertainPerformance Oct 20 '20 at 15:22

1 Answers1

1

Named capture groups are only supported in Node 10+, according to MDN. You need to update your Node version. (Node versions below 10 are very old, it'd be a good idea to update even were it not for this issue)

If for some reason you're not permitted to do that, you can make it a normal capture group rather than a named capture group:

/\?(.*)/

and then extract the first group from the match ([1]). Same thing for extracting the pairs from the query string.

On modern versions of Node, you can also use the more semantic Object.fromEntries instead of reduce:

const params = Object.fromEntries(
  pairs.map(pair => pair.split('='))
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Oh, I didn't even realise my node was on `v8.11.4` lol; I haven't been on this PC in a long time. thanks for the advice. – Johnty Oct 19 '20 at 22:59
  • Sorry, @CertainPerformance I forgot to do so, just done it now; I was rushing around xD – Johnty Oct 22 '20 at 13:57