Forum Moderators: open

Message Too Old, No Replies

Regex Problem

converting bbcodes to html

         

RyanM

10:29 pm on Feb 14, 2006 (gmt 0)

10+ Year Member



Hi I am writing a quick JS funtion to convert BBCodes to HTML. The code that I have is as follows:


test = "[img]http://www.com/image.jpg[/img]";
test.replace("\[img\](.*?)\[/img\]", "<img src='#1' />");
alert(test);

This should return the following:
<img src='http://www.com/image.jpg'>

However it returns:
http://www.com/image.jpg

So obviously its not matching.

test.match("\[img\](.*?)\[/img\]); doesnt work either

DrDoc

10:34 pm on Feb 14, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Two things:

1) the regexp itself needed to be changed
2) even if yours had been correct, it would not have changed anything since you did not assign the replaced string to a variable ;)

<script type="text/javascript">
test = " http:/<!-- www.BestBBS.com -->/www.example.com/image.jpg ";
test = test.replace(/\[img\](.*?)\[\/img\]/g, "<img src=\"$1\" />");
alert(test);
</script>

RyanM

10:54 pm on Feb 14, 2006 (gmt 0)

10+ Year Member



Thats brilliant thanks, does the "g" denote replace variables?

DrDoc

11:06 pm on Feb 14, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



"g" means "replace globally". In other words -- replace all occurances.

RyanM

12:36 am on Feb 15, 2006 (gmt 0)

10+ Year Member



Cheers, your help was invaluable.