BBCode Parser for JavaScript

5.1.0 · active · verified Tue Apr 21

The `js-bbcode-parser` library offers a simple and efficient solution for converting BBCode markup into HTML. Currently, at version 5.1.0, the package demonstrates an active development lifecycle with consistent updates within the v5 series since its major release. Its core strength lies in its configurability, allowing developers to extend the parser with custom BBCode tags and their corresponding HTML output. A crucial distinction is its explicit design choice *not* to include built-in XSS protection; implementers are responsible for sanitizing all user-generated input to prevent potential cross-site scripting vulnerabilities, making it a powerful but security-conscious tool. The library supports a comprehensive set of default BBCode tags, including formatting (`[b]`, `[i]`, `[u]`), headings (`[h1]` to `[h6]`), paragraphs (`[p]`), styling (`[color]`, `[size]`), and media (`[img]`, `[email]`). It also handles attributes like `class` and `data-*` within tags, providing flexibility for styled output. Its simple API makes integration straightforward, either by using a pre-configured default parser instance or by creating custom instances for more fine-grained control over the parsing rules.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic usage of the default parser, how to create and configure a custom parser with new BBCode tags, and highlights the critical need for XSS sanitization.

import bbCodeParser from 'js-bbcode-parser';
import BBCodeParser from 'js-bbcode-parser/src/index.js';

// Use the default pre-configured parser
const defaultParsed = bbCodeParser.parse('Hello [b]World[/b]! This is a [color=#FF0000]red[/color] text.');
console.log('Default Parser Output:', defaultParsed);
// Expected: "Hello <strong>World</strong>! This is a <span style="color:#FF0000">red</span> text."

// Create a custom parser instance and add a custom tag
const customParser = new BBCodeParser({});
customParser.addCode(
  'mention',
  (content, attr) => `<a href="/users/${attr.id}">@${content}</a>`,
  ['id'], // Required attribute
  []    // Optional attributes
);

const customParsed = customParser.parse('[mention id=123]Alice[/mention] says hello.');
console.log('Custom Parser Output:', customParsed);
// Expected: "<a href="/users/123">@Alice</a> says hello."

// IMPORTANT: Sanitize user input before parsing, as this library does not provide XSS protection.
const userInput = '[b]Bold text[/b] and potentially malicious <img src=x onerror=alert(1)> content.';
// In a real application, use a dedicated HTML sanitizer library here, e.g., DOMPurify
// Example of basic (non-robust) sanitization (DO NOT rely on this for production XSS prevention!)
const basicSanitizedInput = userInput.replace(/<script[^>]*>.*?<\/script>/gi, '');
const parsedAndSanitized = bbCodeParser.parse(basicSanitizedInput);
console.log('Sanitized Input Output:', parsedAndSanitized);

view raw JSON →