Jurgo Boemo
Jurgo Boemo

Reputation: 1768

removing html tag's attribute with regexp and backreference

I need to remove the "style" attribute from a html attribute I've achived this goal with this regular expression:

"<div id='mioId'  style='color:black;background-color:red' attr='stuff' class='myClass' />".replace(/style=('|")[^('|")]*\1/, '')

what I would like to do, is using the backreference also to match the content. something like this:

"<div id='mioId'  style='color:black;background-color:red' attr='stuff' class='myClass' />".replace(/style=('|")[^\1]*\1/, '')

in my head this last solution should work, but regular expressions seem not agree with me...

note: I'm note interested in other approach, I just want to understood what I'm doing wrong

Upvotes: 0

Views: 68

Answers (1)

hwnd
hwnd

Reputation: 70722

Backreferences cannot be used inside character classes.

Instead of using a negated character class, you have to use a Negative Lookahead.

.replace(/style=(['"])(?:(?!\1).)*\1/, '')

Upvotes: 2

Related Questions