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!
Asked
Active
Viewed 36 times
1

Mark
- 13
- 1
- 4
2 Answers
1
Try this:
var s = "<blue>Hello, <red>world</red>!</blue>";
s.replace(/<.*?>/g, " ");
Result -> " Hello, world ! "

hardkoded
- 18,915
- 3
- 52
- 64

David Ramos
- 11
- 2
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 `"
"`, the code will output `, world`. I only have to remove tags, world !, ,, . – 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