Search code examples
javascriptsecurityxssbbcode

BBCode with XSS escape?


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&lt;script&gt;alert(1)&lt;/script&gt;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?


Solution

  • 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 {'>':'&gt;', '<':'&lt;', '"':'&quot;'}[a] || a;
        }
        s = s.replace(/[<>"]/g, html);
        s = s.replace(/\[bbcode]((?:http:|ftp:\/)\/\/.*?)\[\/bbcode]/g, '<img src="$1">');
        return s;
    }