homepage Welcome to WebmasterWorld Guest from 54.161.228.29
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
JS script only replaces one instance
BlackRaven




msg:3500275
 3:26 am on Nov 9, 2007 (gmt 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 ++ )
{

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

 

d40sithui




msg:3500829
 5:23 pm on Nov 9, 2007 (gmt 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)";

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

document.write(message);

Fotiman




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

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.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved