There is a string like:
jaksldhfklajsfdhdkjf[bbcode]img url[/bbcode]kjalhdfk<script>alert(1)</script>sdlfjah
…and I want it to become:
jaksldhfklajsfdhdkjf<img src="img url" />kjalhdfk<script>alert(1)</script>sdlfjah
…using JavaScript only.
I can't find a JS library that can do it. Is there a completed library or another way (or different logic) to prevent unsafe input?
The best way to do what you are trying to do is by making escapement replacements before parsing the BBCode.
function escape(s) { // http://escape.alf.nu/
function html(a) {
return {'>':'>', '<':'<', '"':'"'}[a] || a;
}
s = s.replace(/[<>"]/g, html);
s = s.replace(/\[bbcode]((?:http:|ftp:\/)\/\/.*?)\[\/bbcode]/g, '<img src="$1">');
return s;
}