An example input would be "abc".replace(x, /[bc]/g, "[match]"), where x is a variable with the value /[ab]/g, which in that case should return a[match]b.
Sounds like you're looking for capture groups and a replace
callback.
A capture group is a part of the regular expression telling the engine to "capture" the bit that matched that part of it.
A replace
callback is a function that replace
will call for each match, letting you create the replacement text. The function is passed the overall match and any capture groups.
So for instance, if you wanted to match anything between the letters a-z and the numbers 0-9, and do something to the bit in-between:
var result = "afoo9".replace(/([a-z])(.+)([0-9])/g, function(match, c0, c1, c2) {
return c0 + c1.toUpperCase() + c2;
});
([a-z])
means "match any character from a
to z
and capture it"
(.+)
means "match one or more characters here and capture them"
([0-9])
means "match any character from 0
to 9
and capture it" (could also be written (\d)
)
That's quite contrived, of course, and you probably want to match more than one character at each end, but that's a regex detail.
Live example:
var str = "afoo9";
var result = str.replace(/([a-z])(.+)([0-9])/g, function(match, c0, c1, c2) {
return c0 + c1.toUpperCase() + c2;
});
snippet.log("String: " + str);
snippet.log("Result: " + result);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>