1

I have a string with tags. "<blue>Hello, <red>world</red>!</blue>". And I have to get this string without tags using RegExp. I wrote this code, but I think that it can be easier. str.split('<red>').join('').split('</red>').join('').split('</blue>').join('').split('<blue>').join('');
Please, help me!

Mark
  • 13
  • 1
  • 4

2 Answers2

1

Try this:

var s = "<blue>Hello, <red>world</red>!</blue>";
s.replace(/<.*?>/g, " ");
Result -> " Hello,  world ! "
hardkoded
  • 18,915
  • 3
  • 52
  • 64
1

Use .replace(/<\/?(red|blue)>/g, ""):

console.log( "<blue>Hello, <red>world</red>!</blue>".replace(/<\/?(red|blue)>/g, "") )

If you want to match also case insensitive versions of the tags, you just need to insert i after /g. This will not work with attributes or spaces before or after the tag name. If you need it, comment on this answer and I will edit it.

D. Pardal
  • 6,173
  • 1
  • 17
  • 37
  • Yes and no. This code removes everything in <>, so if I have `", world!"`, the code will output `, world`. I only have to remove tags , , , . – Mark Apr 03 '20 at 11:33
  • Man, thank a lot. You are the best. It is what I want – Mark Apr 03 '20 at 12:52