@lynxlynxlynx What do you mean? JS supports RegEx modifiers, dotall is on the track to be added to the spec soon too. Not sure how that relates to doing inline replace.
Did you mean matching groups? Because JS RegEx supports those too.
Here’s a relatively one-liner regex that solves the problem using some of the more advanced, and less known features of JS regex.
@KittenHero Nice, when you said one-liner I was thinking the same thing. Here’s an alternative method to insert variables into the regex source. If you are building a regex string that conditionally includes multiple variable, this can be a lot cleaner than using new
with a concatenation.
This version covers the missing edge case mentioned in my last comment. Also, you don’t need the g
modifier because you’re only doing a single match.
function myReplace(str, before, after) {
return str.replace(/X/i.source.replace(/X/, before), (m) => {
if (/^[A-Z]/.test(m))
return after[0].toUpperCase() + after.slice(1);
if (/^[a-z]/.test(m))
return after[0].toLowerCase() + after.slice(1);
return after;
});
}
-
/X/.source
- references the regex source’s raw string -
replace(/X/, before)
- replacesX
in the source with the value ofbefore
.
The next part leverages another feature of RegEx. The second parameter of Replace can be fed a function. For every matching group (ie surrounded by parentheses) a match variable will be made available in the function.
str.replace(/group1)|(group2)|(group3)/, (m, g1, g2, g3, offset, string) => {
console.log(m);
console.log(g1);
console.log(g2);
console.log(g3);
});
This is fully documented at MDN - String.prototype.replace()
If you need to do a complex replace without additional logic you can use $&, $1, $2, $3 in the second parameter to reference the match, group1, group2, group3, etc.
str.replace(/group1)|(group2)|(group3)/, "$& $1 $2 $3);
The replacement string is whatever you return from the function. By inlining the after
construction logic into this string we can capture before
in the text, construct after
and return the correct version of `after.
Even for an advanced example, this goes pretty far above and beyond the typical usage of RegEx. I only know about this because I use RegExp as the lexer in jquery-csv lib.