Is there a way in the JS regular expression API to rewrite an input such that only matched groups are retained (in order), but which works for an arbitrary regex (including ones that have no capturing groups)?
E.g. for the regex /abc([D-F]+)gh([I-K]+)/
and the input abcFEEDghKIKI
, I'd want the output "FEEDKIKI"
, since those are the captured parts.
However, the input regex could have also been /([a-zA-Z]+)/
which for the same input would just return the original text.
And if the regex was /([0-9]+)/
then the empty string would be returned.
The regular expressions will be generated by a tool, but there are lots of them and I don't want a special case code for different numbers of capturing groups.
Ideally, I'd also be able to access the length of the match in the input somehow too.
I assume there's some way to do it via a callback passed to replace()
(or similar), but it's not clear how/if I can get at the indices of the captured groups (or whether that's even necessary in JS).
Essentially I am trying to replicate the sort of thing you can do via the MatchResult
API in Java, where groups can be iterated over and the start/end indices of captured groups can be found.
Thanks in advance!