Matt
Matt

Reputation: 1757

removing bb codes with regex replace

I am trying to remove BBCode tags through Javascript however I am unable to understand how.

Adding all tags into an array eg:

var bbcodes = ["[b]", "[/b]"];

Then searching through my text and replacing the bbcode with "".

for (i=0; i < bbcodes.length; i++) {
    selTextStrip = selTextStrip.replace(bbcodes[i], ""); 
}

Having realised this will only replace the first occurrence I tried to add expression:

for (i=0; i < bbcodes.length; i++) {
    selTextStrip = selTextStrip.replace(new RegExp(bbcodes[i], 'g'), ""); 
}

However this would do the following:

Change [b]BBCode[/b] into []BBCode[]

How can I change the RegExp to suite all these tags:

"[b]", "[/b]", "[i]", "[/i]", "[u]", "[/u]", "[s]", "[/s]", "[left]", "[/left]", "[center]", "[/center]", "[right]", "[/right]", "[quote]", "[/quote]", "[code]", "[/code]", "[list]", "[/list]", "[img]", "[/img]", "[spoil]", "[/spoil]"

Further to this, If I want to remove the following tags from text -> [color=red]text[/color] what expression would I need to remove both [color=red] and [/color]? Noting that 'red' can change to any length and can also be a hex value ([color=#ff0000]text[/color])

I have tried adding [color=(.*?)] into the array however as before only 'color=' is removed not the #hex value nor the '[]'

Thanks in advance.

Upvotes: 1

Views: 838

Answers (2)

Alexander Pavlov
Alexander Pavlov

Reputation: 32286

text.replace(/\[\/?(?:b|i|u|s|left|center|right|quote|code|list|img|spoil|color).*?\]/g, '')

will also provide the color=foo stripping.

Or use

text.replace(/\[\/?[^\]]*\]/g, '')

to strip all kinds of [foo something] tags.

Upvotes: 2

SomeDude
SomeDude

Reputation: 14238

You can use the regex \[\\?\w*\]

Look at this

Upvotes: 0

Related Questions