-2

Example API - /api/test/regex/?name=ciara
What i want - name=ciara

2 Answers2

0

Try this:

(?<=\?name=)\w+

Regex demo

Alireza
  • 2,103
  • 1
  • 6
  • 19
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