Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply regex replace only within "scope"

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.

like image 504
twharmon Avatar asked Apr 16 '26 17:04

twharmon


1 Answers

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);
like image 186
choz Avatar answered Apr 18 '26 08:04

choz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!