Forum Moderators: open

Message Too Old, No Replies

JS script only replaces one instance

         

BlackRaven

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

10+ Year Member



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 ++ )
{

message=message.replace(bbcode[i],htmlcode[i]);
}

d40sithui

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

10+ Year Member



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)";

message=message.replace(/\(b\)/gi,"<b>");
message=message.replace(/\(\/b\)/gi,"</b>");

document.write(message);

Fotiman

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

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



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.