Aaron Yodaiken
Aaron Yodaiken

Reputation: 19551

Run a regex replace while ignoring (but preserving) a certain character

I think this is easier explained with some examples so...

"*X*helXlo** my \\X world" => "<b>*X*helXlo**</b> my \\X world"
"**helXlo** my \\X world"  => "<b>hello</b> my \\X world"

That is I sort of want something like

str.replace(/(X)?\*(X)?\*(.*)\*(X)?\*(X)?/g, "<b>$1*$2*$3*$4*$5</b>");

but ideally less ugly (looking more like the natural replace(/(\*\*.*\*\*)/g, "<b>$1</b>")). Is this possible?

Upvotes: 0

Views: 32

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149000

If I understand what you're asking for, you definitely don't need all those groups. You could just do this:

str.replace(/X?\*X?\*.*\*X?\*X?/g, "<b>$&</b>")

It's essentially the same pattern, just without the groups. $& represents the entire matched substring.

Alternatively, you could write this as:

str.replace(/(X?\*){2}.*(\*X?){2}/g, "<b>$&</b>")

Upvotes: 2

Related Questions