dthree
dthree

Reputation: 20780

JS Regex replacement - replace fixed text around random string

Given this text:

<span class='green'>foobar</span> something <span class='red'>fizzle</span>

I need to somehow attain this:

<tagA>foobar</tagA> something <tabB>fizzle</tagB>

I basically have to match <span class='green'>*anything*</span> and be able to differentiate it from the red one as well. I have to take this green span on both ends and replace it with a fixed string, but somehow retain whatever text is between the two tags.

I swear I've looked around a ton but have no idea how to find the solution for this with regex.

Upvotes: 0

Views: 163

Answers (1)

buckley
buckley

Reputation: 14109

This should do the trick

Replace

<span class='green'>(.*?)</span>

With

<tagA>$1</tagA>

And do something similar for the class with the value red

Update 1

Response to feedback "What if something contains a newline?"

If I remember correctly JavaScript does not support the "single line mode" / Dot matches line breaks.

<span class='green'>([\s\S]*?)</span>

Update 2

This tweaked regex allows

<span\s+class\s*=\s*['"]green['"]\s*>([^>]*)</\s*span\s*>
  • white space where the html spec is allowing it
  • accepts single as well as double quotes for the attribute values
  • matches the value between the tags using a negated character class which is qualified greedy resulting in better performance generally and is also supported by JavaScript

Upvotes: 1

Related Questions