Using a regular expression should do nicely:
$('#response').html(function() {
return $(this).text().replace(/\[(\/?\w+)\]/g, "<$1>");
});
The benefit is that all tokens are replaced without having to name them individually.
Note that this opens the door for cross site scripting attacks!
If you want to transform tokens in the process (like [b]
to <strong>
) and whitelist them (and you definitely want to whitelist them to migitate XSS vulnerability), use a callback function as the replacement, like this:
$('#response').html(function () {
var map = {
b: "strong",
i: "em",
p: "p"
};
return $(this).text().replace(/\[(\/?)(\w+)\]/g, function ($0, $1, $2) {
if (map.hasOwnProperty($2)) {
return "<" + $1 + map[$2] + ">";
} else {
return $0;
}
});
});
And to make this a jQuery answer, here's how to turn all that into a fancy jQuery plugin for re-use:
$.fn.extend({
unphpbb: (function () {
var map = {
b: "strong",
i: "em",
p: "p"
},
tokens = /\[(\/?)(\w+)\]/g,
replacement = function ($0, $1, $2) {
return map.hasOwnProperty($2) ? "<" + $1 + map[$2] + ">" : $0;
},
replaceTokens = function (i, html) {
return html.replace(tokens, replacement);
};
return function () {
return this.html(replaceTokens);
};
})()
});
used as
$("#response").unphpbb();
Of course using a bbcode parser on the server and sending properly scrubbed HTML to the client is the preferred method for solving this. Doing this on the client with a function like above is inferior in every way.