Pattle
Pattle

Reputation: 6014

Using .replace to replace a any combination of <b><u> and <i> tags

I'm using the .replace JavaScript method to replace <b>, <u> and <i> tags in a string.

var $text = 'This is some <b><u><i>bold underlined italic text</i></u></b>';
$text.replace(new RegExp('<(/?)b><(/?)u><(/?)i>','gmi'), '<div>').replace(new RegExp('<(/?)i><(/?)u><(/?)b>','gmi'), '</div>');

However this is not ideal because it only works if the tags are in that order. it wouldn't work if my string was,

var $text = 'This is some <i><b><u>bold underlined italic text</u></b></i>';

Is there a method I can use that will allow for any combination of these three tags?

Thanks for any help.

Upvotes: 0

Views: 64

Answers (2)

Vbyec
Vbyec

Reputation: 903

You`ll need to remove all b,u,i tags?

$text.replace(/(<\/?(u|i|b)>)/gmi,"")

Upvotes: 1

jPO
jPO

Reputation: 2552

Why not create three RegExp and then just $text.replace(regex1,'foo').replace(regex2,'foo').replace(regex3,'foo') where your regex1...3 would contain only one tag

It is stupid approach though, but also the simplest one and easy to understand, other thing might be to use | quantificator in your regex between all those tags.. e.g EDIT This would create three times the foo, which you don't want.

$regexp = new RegExp('(<(/?)b>)|(<(/?)u>)|(<(/?)i>)','gmi');

EDIT And this option would suit you the best and according to @Vbyec you could write this in even nicer and shorter way

$regexp = new RegExp('(<\/?(u|i|b)>)+','gmi')

Upvotes: 2

Related Questions