js实现ubb
UBB 标签的基本概念
UBB(Universal Bulletin Board)是一种基于文本的标记语言,常用于论坛和社区中。它允许用户通过简单的标签实现文本格式化,如加粗、斜体、链接等。UBB 标签通常由方括号 [] 包围,例如 [b]加粗文本[/b]。
实现 UBB 解析的核心思路
UBB 解析的核心是将 UBB 标签转换为对应的 HTML 标签。可以通过正则表达式匹配 UBB 标签,并将其替换为 HTML 标签。以下是常见的 UBB 标签及其对应的 HTML 实现方式:
常见 UBB 标签的解析方法
加粗标签 [b]
text = text.replace(/\[b\](.*?)\[\/b\]/g, '<strong>$1</strong>');
斜体标签 [i]
text = text.replace(/\[i\](.*?)\[\/i\]/g, '<em>$1</em>');
下划线标签 [u]
text = text.replace(/\[u\](.*?)\[\/u\]/g, '<u>$1</u>');
链接标签 [url]
// 带 URL 的链接
text = text.replace(/\[url=(.*?)\](.*?)\[\/url\]/g, '<a href="$1">$2</a>');
// 不带 URL 的链接
text = text.replace(/\[url\](.*?)\[\/url\]/g, '<a href="$1">$1</a>');
图片标签 [img]
text = text.replace(/\[img\](.*?)\[\/img\]/g, '<img src="$1" alt="图片" />');
颜色标签 [color]
text = text.replace(/\[color=(.*?)\](.*?)\[\/color\]/g, '<span style="color:$1">$2</span>');
完整 UBB 解析函数示例
以下是一个完整的 UBB 解析函数,支持常见的 UBB 标签:
function parseUBB(text) {
// 加粗
text = text.replace(/\[b\](.*?)\[\/b\]/g, '<strong>$1</strong>');
// 斜体
text = text.replace(/\[i\](.*?)\[\/i\]/g, '<em>$1</em>');
// 下划线
text = text.replace(/\[u\](.*?)\[\/u\]/g, '<u>$1</u>');
// 链接(带 URL)
text = text.replace(/\[url=(.*?)\](.*?)\[\/url\]/g, '<a href="$1">$2</a>');
// 链接(不带 URL)
text = text.replace(/\[url\](.*?)\[\/url\]/g, '<a href="$1">$1</a>');
// 图片
text = text.replace(/\[img\](.*?)\[\/img\]/g, '<img src="$1" alt="图片" />');
// 颜色
text = text.replace(/\[color=(.*?)\](.*?)\[\/color\]/g, '<span style="color:$1">$2</span>');
// 换行(UBB 通常用 \n,HTML 用 <br>)
text = text.replace(/\n/g, '<br>');
return text;
}
安全性注意事项
直接解析 UBB 并插入 HTML 可能存在 XSS(跨站脚本攻击)风险。为了避免安全问题,建议对输入的文本进行转义处理:
function escapeUBB(text) {
return text.replace(/</g, '<').replace(/>/g, '>');
}
// 使用方式
const safeText = escapeUBB(originalText);
const html = parseUBB(safeText);
扩展 UBB 功能
如果需要支持更多 UBB 标签(如表格、列表等),可以扩展正则表达式规则。例如:
列表标签 [list]
text = text.replace(/\[list\](.*?)\[\/list\]/g, '<ul>$1</ul>');
text = text.replace(/\[\*\](.*?)(\n|$)/g, '<li>$1</li>');
引用标签 [quote]

text = text.replace(/\[quote\](.*?)\[\/quote\]/g, '<blockquote>$1</blockquote>');
测试示例
const ubbText = '[b]加粗文本[/b] [i]斜体文本[/i] [url=https://example.com]链接[/url]';
const htmlText = parseUBB(ubbText);
console.log(htmlText);
// 输出: <strong>加粗文本</strong> <em>斜体文本</em> <a href="https://example.com">链接</a>
通过以上方法,可以实现基本的 UBB 解析功能,并根据需求扩展更多标签支持。






