JSFiddle - React, Tailwind, and code Playground

by Gwyn Milcote

HTML

https://github.com/DasRed/js-bbcode-parser
<br>
<pre><code>
// use to create a clean parser
const parserA = bbCodeParser.create{}, {})

// configure the default parser with
bbCodeParser.setCodes({});

console.log(bbCodeParser.parse('This is a text[br]with HTML Break.'));

You can provide your own BBCodes. The key of the codes object must be a regex part and the value is the replacement.

import bbCodeParser from 'js-bbcode-parser';

const parser = bbCodeParser.create({
    '\\[br\\]': '<<b>b</b>r>'
});
console.log(parser.parse('This is a text[br]with HTML Break.'));
</code></pre>

<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

class BBCode {
    
    constructor(codes){
        this.codes = [];
        this.setCodes(codes);
    }

    parse(text){
        return this.codes.reduce((text, code) => text.replace(code.regexp, code.replacement), text);
    }

    add(regex, replacement){
        this.codes.push({
            regexp: new RegExp(regex, 'igm'),
            replacement: replacement
        });
        return this;
    }

    setCodes(codes){
        this.codes = Object.keys(codes).map(function(regex){
            const replacement = codes[regex];
            return {
                regexp: new RegExp(regex, 'igm'),
                replacement: replacement
            };
        }, this);
        return this;
    }
}

let bbcodeParser = new BBCode({
    '\\[br\\]': '<br>',
    '\\[hr\\]': '<hr>',

    '\\[b\\](.+?)\\[/b\\]': '<strong>$1</strong>',
    '\\[i\\](.+?)\\[/i\\]': '<em>$1</em>',
    '\\[u\\](.+?)\\[/u\\]': '<u>$1</u>',
    '\\[sup\\](.+?)\\[/sup\\]': '<sup>$1</sup>',
    '\\[sub\\](.+?)\\[/sub\\]': '<sub>$1</sub>',
    '\\[code\\](.+?)\\[/code\\]': '<code>$1</code>',
    '\\[pre\\](.+?)\\[/pre\\]': '<pre>$1</pre>',
    '\\[center\\](.+?)\\[/center\\]': '<div style="text-align:center">$1</div>',
    
    '\\[table\\](.+?)\\[/table\\]': '<table>$1</table>',
    '\\[tr\\](.+?)\\[/tr\\]': '<tr>$1</tr>',
    '\\[td\\](.+?)\\[/td\\]': '<td>$1</td>',
    
    '\\[quote\\](.+?)\\[/quote\\]': '<blockquote>$1</blockquote>',
    '\\[quote=(.+?)\\](.+?)\\[/quote\\]': '<blockquote><b>$1:</b><br><br>$2</blockquote>',

    '\\[h1\\](.+?)\\[/h1\\]': '<h1>$1</h1>',
    '\\[h2\\](.+?)\\[/h2\\]': '<h2>$1</h2>',
    '\\[h3\\](.+?)\\[/h3\\]': '<h3>$1</h3>',
    '\\[h4\\](.+?)\\[/h4\\]': '<h4>$1</h4>',
    '\\[h5\\](.+?)\\[/h5\\]': '<h5>$1</h5>',
    '\\[h6\\](.+?)\\[/h6\\]': '<h6>$1</h6>',

    '\\[p\\](.+?)\\[/p\\]': '<p>$1</p>',
    '\\[font=(.+?)\\](.+?)\\[/font\\]': '<span style="font-family:$1">$2</span>',

    '\\[color=(.+?)\\](.+?)\\[/color\\]':  '<span...