BBCode Parser for JavaScript
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
-
TypeError: bbCodeParser.parse is not a function
cause Incorrect import or CommonJS require statement attempting to call 'parse' directly on the module object instead of the default export.fixFor CommonJS, use `const bbCodeParser = require('js-bbcode-parser').default;`. For ES Modules, ensure you are importing the default export correctly: `import bbCodeParser from 'js-bbcode-parser';`. -
ReferenceError: BBCodeParser is not defined
cause Attempting to create a new parser instance using `new BBCodeParser()` without importing the class constructor from its specific path.fixImport the class constructor with `import BBCodeParser from 'js-bbcode-parser/src/index.js';`. -
Error: Unknown BBCode tag [mycustomtag]
cause A BBCode tag was used in the input string that has not been registered with the parser instance.fixRegister the custom BBCode tag using `parser.addCode('mycustomtag', (content) => `<div>${content}</div>');` before parsing the string.
Warnings
- breaking Major API changes occurred between v2.x and v5.x, particularly concerning parser instantiation and configuration. Users upgrading from v2.x will need to refactor their code, especially around how custom codes are defined and applied.
- gotcha js-bbcode-parser explicitly does not sanitize user input for XSS vulnerabilities. Developers MUST implement their own robust sanitization measures on the output HTML, especially when parsing untrusted user-generated content.
- gotcha Importing the class constructor `BBCodeParser` requires a specific path (`js-bbcode-parser/src/index.js`). While documented, relying on `src` paths might be less stable than official entry points for future versions.
Install
-
npm install js-bbcode-parser -
yarn add js-bbcode-parser -
pnpm add js-bbcode-parser
Imports
- bbCodeParser
import { bbCodeParser } from 'js-bbcode-parser';import bbCodeParser from 'js-bbcode-parser';
- BBCodeParser
import { BBCodeParser } from 'js-bbcode-parser';import BBCodeParser from 'js-bbcode-parser/src/index.js';
- bbCodeParser (CommonJS)
const bbCodeParser = require('js-bbcode-parser');const bbCodeParser = require('js-bbcode-parser').default;
Quickstart
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);