JAVASCRIPT
Convert BBCode to HTML for Rich Text Display
Transform BBCode tags like `[b]`, `[i]`, and `[url]` into their corresponding HTML elements (`<strong>`, `<em>`, `<a>`) using JavaScript regex replacement.
function convertBbcodeToHtml(bbcodeString) {
let htmlString = bbcodeString;
htmlString = htmlString.replace(/\\[b\\](.*?)[\/b\\]/gi, '<strong>$1</strong>');
htmlString = htmlString.replace(/\\[i\\](.*?)[\/i\\]/gi, '<em>$1</em>');
htmlString = htmlString.replace(/\\[u\\](.*?)[\/u\\]/gi, '<u>$1</u>');
htmlString = htmlString.replace(/\\[url=(.*?)\\](.*?)[\/url\\]/gi, '<a href="$1">$2</a>');
htmlString = htmlString.replace(/\\[color=(.*?)\\](.*?)[\/color\\]/gi, '<span style="color:$1;">$2</span>');
return htmlString;
}
const bbcodeText = "This is some [b]bold text[/b], [i]italic text[/i], and a [url=https://example.com]link[/url] in [color=red]red[/color].";
const htmlOutput = convertBbcodeToHtml(bbcodeText);
console.log(htmlOutput);
How it works: This JavaScript function `convertBbcodeToHtml` uses a series of regular expression `replace()` calls to transform common BBCode tags into their equivalent HTML. Each regex targets a specific BBCode pattern, like `[b]...[/b]`, and replaces it with the corresponding HTML element (`<strong>...</strong>`), utilizing capturing groups (`$1`, `$2`) to preserve the content or attributes within the tags. This is highly useful for rendering user-generated content from forums or old CMS platforms.