Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

JS script only replaces one instance

3:26 am on Nov 9, 2007 (gmt 0)

Full Member

10+ Year Member

joined:June 16, 2004
votes: 0

my js function only replaces one instance of the bbcode array, so say the message text is "(b)text(/b) (b)text(/b)" the output would be "<b>text</b> (b)text(/b)". Any help appreciated. Thanks


var message=document.getElementById('message').value;
var bbcode = new Array("(b)","(/b)");
var htmlcode = new Array("<b>","</b>");

for(var i = 0 ; i < bbcode.length ; i ++ )


5:23 pm on Nov 9, 2007 (gmt 0)

Preferred Member

10+ Year Member

joined:Jan 16, 2007
votes: 0

this is because it stops after reaching the end of your array, which is only enough for 1 change. try this.

var message="(b)text(/b)(b)Text2(/b)";



6:38 pm on Nov 9, 2007 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
votes: 21

Your bbcode array should contain RegExp values, not string values. Try this:

var bbcode = [/\(b\)/gi, /\(\/b\)/gi];

The first pattern: /\(b\)/gi
That says match the literal '(' followed by a 'b' followed by a literal ')', and the 'g' attribute makes it 'Global' (matches all instances). The 'i' attribute will make it case-insensitive, so you could do:

(b)bold(/b) (B)bold(/B) (b)bold(/B)

and you'd end up with:

<b>bold</b> <b>bold</b> <b>bold</b>

The second pattern: /\(\/b\)/gi
That says match the literal '(' followed by the literal '/' followed by 'b' followed by the literal ')'. Again, the 'g' makes it global and the 'i' makes it case insensitive.