Greasy Fork is available in English.
Parse BBCode into AST and convert into HTML
بۇ قوليازمىنى بىۋاسىتە قاچىلاشقا بولمايدۇ. بۇ باشقا قوليازمىلارنىڭ ئىشلىتىشى ئۈچۈن تەمىنلەنگەن ئامبار بولۇپ، ئىشلىتىش ئۈچۈن مېتا كۆرسەتمىسىگە قىستۇرىدىغان كود: // @require https://update.greasyfork.org/scripts/549682/1681117/BBCode%20Parser.js
A BBCode parser without any built-in parsing rules, allowing users to implement their own rules.
const parser = new BBCodeParser.BBCodeParser();
A rule for [url=URL]CONTENT[/url] and [url]URL_AS_CONTENT[/url] can be registered like this:
parser.register({
'url': {
openTag(params, content) {
let url = params ?? content;
url = url.startsWith('http://') || url.startsWith('https://') ? url : 'http://' + url;
return `<a href="${ url }" target="_blank">`;
},
closeTag(params, content) {
return '</a>'
},
}
});
A rule for [b]CONTENT[/b] can be registered like this:
parser.register({
'b': {
openTag(params, content) {
return '<b>';
},
closeTag(params, content) {
return '</b>';
},
},
});
And yes, they can be registered with one call:
parser.register({
'url': {
openTag(params, content) {
let url = params ?? content;
url = url.startsWith('http://') || url.startsWith('https://') ? url : 'http://' + url;
return `<a href="${ url }" target="_blank">`;
},
closeTag(params, content) {
return '</a>'
},
},
'b': {
openTag(params, content) {
return '<b>';
},
closeTag(params, content) {
return '</b>';
},
},
});
const result = parser.parse('[b]Hello[/b], [url=https://example.com/]bbcode[/url]');
// You can access html or ast / nodes in result object, like
console.log(result.html);
console.log(result.html_ast);
console.log(result.ast);
// Check if there's any error while paring
console.log(result.errors);
Please refer to JSDoc in source code.
(Sadly comments are written in Chinese)