0

This question is for general purpose, and no, "you should never regex html"...

What is the regex to remove an empty attribute, such as

class="" or class="   "

without knowing the number of whitespaces inbetween " "?

Plus: Leaving the class tag untouched if there are other chars inside?


I got a solution for complicated regex yesterday, however, I was not able to strip that down to the specific case mentioned above.

Thank you!

Community
  • 1
  • 1
Avatar
  • 14,622
  • 9
  • 119
  • 198

3 Answers3

5

Try with the following regex:

/class="\s*?"/
elclanrs
  • 92,861
  • 21
  • 134
  • 171
2

If you don't care about checking whether or not it's actually inside an HTML tag, you can use:

[a-z]+="\s*"

This could be used with .replace() such as:

str = str.replace(/[a-z]+="\s*"/ig, '');

The i will ignore case while the g will "replace" all instances matched.

newfurniturey
  • 37,556
  • 9
  • 94
  • 102
1

Replace /class="\s*"/ with an empty string.

skunkfrukt
  • 1,550
  • 1
  • 13
  • 22