0

I have a string that looks like this:

const string = 'test_string%name=peter&age=18&foo=bar&lol=loli_copter';

I want to write a regex to get name and the age from this string and their values.

const result = 'name=peter&age=18;

I have tried the following but with no luck:

const result = string.match(/(?<=name\s+).*?(?=\s+age)/gs);

Can anyone help or point me in the right direction?

peter flanagan
  • 9,195
  • 26
  • 73
  • 127

4 Answers4

1

We can use string match here along with a regex pattern which targets the name and age keys, along with their RHS values.

var string = 'test_string%name=peter&age=18&foo=bar&lol=loli_copter';
var parts = string.match(/\b(?:name|age)=[^&]+/g);
var output = parts.join('&');
console.log(output);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

You could just match "any characters except &" for name and "any number of digits" for age. e.g.

name=([^&]+)&age=(\d+)

const string = 'test_string%name=peter&age=18&foo=bar&lol=loli_copter';
const data = string.match(/name=([^&]+)&age=(\d+)/);

console.log(data[1], data[2]) // peter 18
Fraser
  • 15,275
  • 8
  • 53
  • 104
  • This coincidentally happens to work with the query string as given, but will fail should `name` and `age` appear in any other order within the query string. – Tim Biegeleisen Apr 14 '22 at 06:58
  • Yes, obviously - but why would you ever presume they would have any other order than the one specified? It would also fail if the age was `bronze` or `iron` rather than a number... – Fraser Apr 14 '22 at 07:01
0
const string = 'test_string%name=peter&age=18&foo=bar&lol=loli_copter';
const name = string.match(/name=([^&]*)/)[1];
const age = string.match(/age=([^&]*)/)[1];

console.log(name, age)

Output: peter 18

ankitbatra22
  • 417
  • 2
  • 5
0

If your fields are always in this order (so name is always directly before age, nothing ever between, order always the same), you can use this much simpler regex:

name=[^&]*&age=[^&]*

it searches for values consisting of any characters except the ampersand, even empty values would be OK.

But if you have the possibility of different order or intermediate fields, then you better split the string by the delimiters (% and &) and evaluate the field names individually to find out the right values.

cyberbrain
  • 3,433
  • 1
  • 12
  • 22