BBCode Parser

Parse BBCode into AST and convert into HTML

目前為 2025-09-16 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.greasyforks.org/scripts/549682/1661583/BBCode%20Parser.js

作者
PYUDNG
版本
0.1
建立日期
2025-09-16
更新日期
2025-09-16
尺寸
24.9 KB
授權條款
GPL-3.0-or-later

A BBCode parser without any built-in parsing rules, allowing users to implement their own rules.

Usage

1. First of all, create parser

const parser = new BBCodeParser();

2. Implement and register parsing rules

A rule for [url=URL]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:
``` javascript
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>';
        },
    },
});

3. Parse bbcode (and get html if need)

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);

Types

Please refer to JSDoc in source code.

长期地址
遇到问题?请前往 GitHub 提 Issues。