removing BBcode from textarea with Javascript

会有一股神秘感。 提交于 2019-12-11 13:51:48

问题


I'm creating a small javscript for phpBB3 forum, that counts how much character you typed in. But i need to remove the special characters(which i managed to do so.) and one BBcode: quote

my problem lies with the quote...and the fact that I don't know much about regex.

this is what I managed to do so far but I'm stranded:

http://jsfiddle.net/emjkc/

var text = '';
var char = 0;


  text = $('textarea').val();
  text = text.replace(/[&\/\\#,+()$~%.'":*?<>{}!?(\r\n|\n|\r)]/gm, '');
  char = text.length;
  $('div').text(char);
$('textarea').bind('input propertychange', function () {

    text = $(this).val();
    text = text.replace(/[&\/\\#,+()$~%.'":*?<>{}!?\-\–_;(\r\n|\n|\r)]/gm, '');

    char = text.length;
    $('div').text(char);
});

回答1:


You'd better write a parser for that, however if you want to try with regexes, this should do the trick:

text = $('textarea').val();
while (text.match(/\[quote.*\[\/quote\]/i) != null) {
   //remove the least inside the innermost found quote tags 
   text = text.replace(/^(.*)\[quote.*?\[\/quote\](.*)$/gmi, '\$1\$2');
}
// now strip anything non-character
text = text.replace(/[^a-z0-9]/gmi, '');



回答2:


I'm not sure if this would work, but I think you can replace all bbcodes with a regex like this:

var withoutBBCodes = message.replace(/\[[^\]]*\]/g,"");

It just replaces everything like [any char != ']' goes here]

EDIT: sorry, didn't see that you only want to replace [quote] and not all bbcodes:

var withoutBBQuote = message.replace(/\[[\/]*quote[^\]]*\]/g,"");

EDIT: ok, you also want quoted content removed:

while (message.indexOf("[quote") != -1) {
    message = message.replace(/\[quote[^\]]*\]((?!\[[[\/]*quote).)*\[\/quote\]/g,"");
}

I know you already got a solution thanks to @guido but didn't want to leave this answer wrong.



来源:https://stackoverflow.com/questions/14956837/removing-bbcode-from-textarea-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!