Is there a way in the JS regex API to rewrite the input so that only matching groups are kept (in order), but it works with arbitrary regexes (including regexes without capturing groups)?
For example for the regular expression /abc([D-F] )gh([I-K] )/
and input abcFEEDghKIKI
, I want to output "FEEDKIKI"
, because these are the captured parts.
However, the input regular expression can also be /([a-zA-Z] )/
, which will just return the original text for the same input.
If the regular expression is /([0-9] )/
, an empty string will be returned.
The regex will be generated by the tool, but there are many regexes and I don't want special case code for different numbers of capturing groups.
Ideally I would also be able to access the length of the match in the input somehow.
I'm assuming there is some way to accomplish this via a callback passed to replace()
(or similar), but it's not clear how/if I can get the index of the capturing group (or in JS whether it is necessary).
Essentially, I'm trying to replicate what you can do via the MatchResult
API in Java, where groups can be iterated over and the start/end index of the capturing group can be found. < /p>
Thanks in advance!
Discover: How to access JavaScript regular expressions? It looks like (at least initially) using
exec()
will do what I want.