Example API - /api/test/regex/?name=ciara
What i want - name=ciara
Asked
Active
Viewed 251 times
-2

Sweetie Panav
- 22
- 3
2 Answers
0
We cannot use capturing group here, because a repeated capture group will only store the last match that it found. Every time it makes a match, it will overwrite the previous match with the one it just found.
So, we need to go with 2 step solution, first we validate the URL, then use matchAll
to find all references:
const regexp = /(?:(?:\&|\?)([^=]+)\=([^&]+))/g;
const str = '/api/test/regex/?name=ciara&p=q&r=s&t=u';
const array = [...str.matchAll(regexp)];
console.log(array);
This will give you:
> Array [Array ["?name=ciara", "name", "ciara"], Array ["&p=q", "p", "q"], Array ["&r=s", "r", "s"], Array ["&t=u", "t", "u"]]
Since we have an array now, we just need to iterate it to get all query params.
Following regex
can be used validate existence of proper query strings:
\/?\?([^=]+)\=([^&]+)(?:\&([^=]+)\=([^&]+))*$

g-217
- 2,069
- 18
- 33
\w.+)$ $s;– Sweetie Panav Nov 02 '20 at 10:58