How can I apply regex only within a certain scope, like between two **'s?
I want to use JavaScript to change this
**
_a_ _b_ _c_
-d- -e- -f-
**
_a_
into this
**
{a} {b} {c}
(d) (e) (f)
**
_a_
Notice that the desired result is that _a_ is not changed outside of the "scope".
I can do this much
str
.replace(/_(.*?)_/g, "{$1}")
.replace(/-(.*?)-/g, "($1)")
but this will replace everywhere, even outside of the two **'s.
One way to achieve this and it's simpler for me is to extract the string inside your delimiter **, and replace it with your existing regexes (which already works).
E.g.
var str = `**
_a_ _b_ _c_
-d- -e- -f-
**
_a_`;
var result = str.replace(/\*\*(\s|.)+\*\*/g, function (x) {
return x
.replace(/_(.*?)_/g, "{$1}")
.replace(/-(.*?)-/g, "($1)");
});
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With