0

I was trying to match a simple string with a simple RegExp, like this

let html = '<td>Amount</td><td>23</td>';
let rx = /<td>Amount<\/td><td>(.*)<\/td>/gi;
console.log(html.match(rx));

I got

[ '<td>Amount</td><td>23</td>' ]

instead of the expected

[
  '<td>Amount</td><td>23</td>',
  '23',
  index: 0,
  input: '<td>Amount</td><td>23</td>',
  groups: undefined
]

I can't find a simple and straight forward answer for this on StackOverflow.

Why do I get the entire string instead of the capturing group in the result?

Magnus
  • 17,157
  • 19
  • 104
  • 189
  • Note: [matchAll](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll) works with a `g` flag – adiga Mar 04 '20 at 14:31

1 Answers1

0

As it turns out, using the modifier /g with .match() will return the entire string instead of the capturing groups.

So simply removing g from the RegEx did the trick:

let rx = /<td>Amount<\/td><td>(.*)<\/td>/i;
Magnus
  • 17,157
  • 19
  • 104
  • 189
  • the .* in your capture group is greedy. if you change it to .*? you should see better results as it should stop at the first <\/td> match. let rx = /Amount<\/td>(.*?)<\/td>/i; – Jpirok Mar 04 '20 at 14:30