If you want to replace with regular html tags and restrict to only specific BB tags. This is how it's done with a little help from jQuery and Regular Expression:
const replaceBBCodeAsElements = (jElement, tagMapping = {}) =>
jElement.html(jElement.html().replace(/\[(?<tag>\w+)\](.+?)\[\/\k<tag>\]/g,
(...{ 0: original, 1: tagName, 2: tagContent }) =>
tagMapping.hasOwnProperty(tagName) ? $(tagMapping[tagName]).html(tagContent)[0].outerHTML : original
));
And here is an example of using this function:
const replaceBBCodeAsElements = (jElement, tagMapping = {}) =>
jElement.html(jElement.html().replace(/\[(?<tag>\w+)\](.+?)\[\/\k<tag>\]/g,
(...{ 0: original, 1: tagName, 2: tagContent }) =>
tagMapping.hasOwnProperty(tagName) ? $(tagMapping[tagName]).html(tagContent)[0].outerHTML : original
));
const config = {
'a': '<div class="tag some-special-a-tag" />',
'object': '<span class="tag some-special-object-tag" />',
'pre': '<p class="tag some-special-pre-tag" />',
'test': '<div data-hello="world" class="tag some-special-test-tag" />',
};
$("#input").bind("input", function() {
const jRes = $("#result");
jRes.text(this.value);
replaceBBCodeAsElements(jRes, config);
}).trigger('input');
#input {
width: 400px;
height: 100px;
}
#result {
white-space: pre-wrap;
}
.tag {
display: inline-block;
background: rgba(0,0,0,.1);
padding: 0 4px;
border-radius: 5px;
font-family: monospace;
font-weight: bold;
margin: 0;
box-shadow: 0 0 10px 0 rgba(0,0,0,.6);
}
.some-special-a-tag {
background: rgba(255,0,0,.1);
}
.some-special-object-tag {
background: rgba(0,255,0,.1);
}
.some-special-pre-tag {
background: rgba(0,0,255,.1);
}
.some-special-test-tag {
background: rgba(0,255,255,.1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="input">This <p>is</p>
a [a]test[/a] text [pre]with[/pre] [b]some[/b] va[test]lu[/test]e.
And this is how it looks [object]when a [pre]tag inside[/pre] other[/object] tag</textarea>
<div id="result"></div>
The above example, will parse only [a]
, [object]
, [pre]
and [test]
BB tags and convert them according to the creation element they are pointing to.
Note, that the minimum required version of JS is ES2018, because of the RegExp Named Group support.