JSFiddle - React, Tailwind, and code Playground
by Gwyn Milcote
HTML
https://github.com/wGEric/phpBB-BBCode-Javascript-Parser
<br><br>To convert BBCode to HTML, use this instruction:
<br>
<code>var html = bbcodeParser.bbcodeToHtml('string with BBCode');</code>
<br>
To convert HTML to BBCode, use this instruction:
<br>
<code>var bbcode = bbcodeParser.htmlToBBCode('string with HTML');</code>
<br>
You can add more BBCode tags using this syntax:
<br>
<code>bbcodeParser.addBBCode('bbcode syntax', 'html syntax');</code>
<br>
For example...
<br>
<code>
bbcodeParser.addBBCode('[header]{TEXT}[/header]', '<<b>h</b>eader>{TEXT}</<b>h</b>eader>');
bbcodeParser.addBBCode('[div id="{IDENTIFIER}"]{TEXT}[/div]', '<<b>d</b>iv id="{IDENTIFIER}">{TEXT2}</<b>d</b>iv>');
</code>
<p>
Type BBCode here...<br>
<textarea id='test_bbcode'>..[b]bold[/b] ...</textarea>
</p>
And <button id='convert_button'>click</button> to output HTML here:<br>
<textarea id='test_html'>...</textarea>
JavaScript
var BBCodeHTML = function(){
var me = this; // Object instance
var token_match = /{[A-Z_]+[0-9]*}/ig;
// Regular expressions for the different BBCode tokens.
var tokens = {
'URL' : '((?:(?:[a-z][a-z\\d+\\-.]*:\\/{2}(?:(?:[a-z0-9\\-._~\\!$&\'*+,;=:@|]+|%[\\dA-F]{2})+|[0-9.]+|\\[[a-z0-9.]+:[a-z0-9.]+:[a-z0-9.:]+\\])(?::\\d*)?(?:\\/(?:[a-z0-9\\-._~\\!$&\'*+,;=:@|]+|%[\\dA-F]{2})*)*(?:\\?(?:[a-z0-9\\-._~\\!$&\'*+,;=:@\\/?|]+|%[\\dA-F]{2})*)?(?:#(?:[a-z0-9\\-._~\\!$&\'*+,;=:@\\/?|]+|%[\\dA-F]{2})*)?)|(?:www\\.(?:[a-z0-9\\-._~\\!$&\'*+,;=:@|]+|%[\\dA-F]{2})+(?::\\d*)?(?:\\/(?:[a-z0-9\\-._~\\!$&\'*+,;=:@|]+|%[\\dA-F]{2})*)*(?:\\?(?:[a-z0-9\\-._~\\!$&\'*+,;=:@\\/?|]+|%[\\dA-F]{2})*)?(?:#(?:[a-z0-9\\-._~\\!$&\'*+,;=:@\\/?|]+|%[\\dA-F]{2})*)?)))',
'LINK' : '([a-z0-9\-\./]+[^"\' ]*)',
'EMAIL' : '((?:[\\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*(?:[\\w\!\#$\%\'\*\+\-\/\=\?\^\`{\|\}\~]|&)+@(?:(?:(?:(?:(?:[a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(?:\\d{1,3}\.){3}\\d{1,3}(?:\:\\d{1,5})?))',
'TEXT' : '(.*?)',
'SIMPLETEXT' : '([a-zA-Z0-9-+.,_ ]+)',
'INTTEXT' : '([a-zA-Z0-9-+,_. ]+)',
'IDENTIFIER' : '([a-zA-Z0-9-_]+)',
'COLOR' : '([a-z]+|#[0-9abcdef]+)',
'NUMBER' : '([0-9]+)'
};
// Matches for BBCode to HTML.
var bbcode_matches = [];
// HTML templates for HTML to BBCode.
var html_tpls = [];
// Matches for HTML to BBCode.
var html_matches = [];
// BBCode templates for BBCode to HTML.
var bbcode_tpls = [];
/**
* Turns a bbcode into a regular rexpression by changing the tokens into
* their regex form
*/
var _getRegEx = function(str) {
var matches = str.match(token_match);
var nrmatches = matches.length;
var i = 0;
var replacement = '';
if (nrmatches <= 0) {
return new RegExp(preg_quote(str), 'g'); // no tokens so return the escaped string
}
for(; i < nrmatches; i += 1) {
// Remove {, } and numbers from the token so it can match the
...