I'm working on a project to allow users to perform dynamic regular expression replacements of strings. The primary "mode of operation" is intended to be as follows:
- User enters a search string which includes capture-groups (
(foo)) - User enters a replacement string which includes capture-group references (
$1,$2, ...) - The final output string follows the format of the replacement string exactly (somewhat comparable to
printfstring formatting in C), as opposed to the format of the input string.
So, for example, the following parameters/output would be expected:
| What? | Value |
|---|---|
| Input | abc def ghi jkl mno |
| Search | (\S+) ghi (\S+) |
| Replacement (*) | $1 - $2 |
| Output | def - jkl |
(*) It seems the term "replacement" leads to confusion for some. To clarify, this is NOT quite the same as a replacement pattern such as one used with e.g. x.replace(), but more like a formatting / output pattern, or, more verbosely: a pattern where you build an entirely new string from scratch, using references to substrings you've captured with the search pattern, ignoring whatever other text is in the original input string. In other words, it's not an inline replacement, but a full replacement.
The idea behind this, is that the user would only have to enter the bare minimum pattern to capture the exact parts they want, rather than (often times) including parts into the search pattern that are just omitted in the replacement.
In the example above, simply adding .* to the beginning and end of the Search parameter and using String.prototype.replace() would essentially accomplish precisely this. However, manipulating the original user-supplied search-string seems like not the best idea, and prone to a lot of gotchas since regex patterns can be quite complex.
So, I was wondering if there are any internal utility functions/methods readily available in JavaScript to safely perform this kind of regex string transformation? I looked around for a while, but maybe I'm just not using the right keywords... Even if there isn't an elegant approach primarily using core JavaScript functions, other (safe!) approaches are still welcome of course.