my BBCode parser will only replace a smiley once
I have a textfield with an onkeyup event so everytime a key is pressed it will update the preview.
The textfield can contain BBCode like [b] or [i] and this will be parsed fine but smileys, like :smile:, will only be replaced once with a <img /> tag and then if you would type :smile: again it would just dispay :smile: instead of replacing it.
this is my code:
Any help would be appreciated.
str = str.replace(BBCode, '<img src="'+src+'.gif" />');
//getting BBCode to be parsed//
str = document.getElementById(input).innerHTML;
//adding line breaks//
str = str.replace(/\n\r?/g, '<br />');
str = str.replace(/\[b\](.*?)\[\/b\]/ig, "<b>$1</b>");
str = str.replace(/\[i\](.*?)\[\/i\]/ig, "<i>$1</i>");
str = str.replace(/\[u\](.*?)\[\/u\]/ig, "<u>$1</u>");
//setting smiley codes to be replaced//
//returning the parsed BBCode as HTML//
document.getElementById(output).innerHTML = str;
Ah, I've had this bug many times too. It turns out, str.replace only replaces the first occurrence. You have to code your own "replaceAll" function.
how you mean? because if I type multyple [b] or [i] then they are ALL replaced but with the smileys only the first one gets replaced
All of the [b], [i], and [u] were replaced because you replaced them using regular expressions with the /g flag specified; that makes the search and replace repeat until no more matches are found.
However, in the :smile: and :spider:, you're using strings with the str.replace method. It's totally acceptable, it just won't continue after the first match. You've got three options here:
1. The easiest and cleanest option, use regular expressions with :smile: and :spider:, something like /:smile:/g and /:spider:/g
2. Write a replaceAll function.
3. I'm not positive, but I think str.replace() may be able to take a third parameter, where you can specify "g" for global. See https://developer.mozilla.org/en/Cor...String/replace
You'll also need to change your addSmiley function to take str as a parameter, and return the new value, and then the parse() will have to assign the result back into it's own str variable. It seems complicated but learning it now will save you days of frustration in the future.
var str = document.getElementById(input).innerHTML;
The first option you said did the job ^^
I replaced this:
now it will replace all until no more matches.
and I actually did set var str;
I set it at the beginning of the page where I set all my variables.
Thanks for your help, works like a charm now:
However, it only works in IE and not in mozilla, mozilla can't use <body onkeyup="function();"> ???
Also, would it be better to first parse the bbcode then put it in the database or should I put the bbcode in the database and parse it right before page is viewed?
Last edited by sicle; 07-26-2009 at 03:48 PM.
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)