Vinz243
Vinz243

Reputation: 9938

Regex replace groups multiple times

I am trying to remove all html tags using this regex:

<.+>(.+)</.+>

Regular expression visualization

And I replace like this:

"<b onclick=\"foo\">Foo</b> bar".replace(new RegExp("\\<.{1,}\\>(.{1,})\\</.{1,}\\>", "g"), "$1")

This works fine, however, this doesnt work:

"<b onclick=\"foo\">Foo</b> bar <b>hello</b>".replace(new RegExp("\\<.{1,}\\>(.{1,})\\</.{1,}\\>", "g"), "$1")

Since I get hello

Upvotes: 0

Views: 74

Answers (2)

zx81
zx81

Reputation: 41838

You can do this:

result = subject.replace(/<[^>]*>/g, "");

Explanation

  • Match the character “<” literally <
  • Match any character that is NOT a “>” [^>]*
    • Between zero and unlimited times, as many times as possible, giving back as needed (greedy) *
  • Match the character “>” literally >

Upvotes: 0

aelor
aelor

Reputation: 11116

use lazy not greedy

<.+?>

along with the g modifier

like this :

"<b onclick=\"foo\">Foo</b> bar <b>hello</b>".replace(/<.+?>/g,'');

output:

Foo bar hello

Upvotes: 1

Related Questions