petjelinux petjelinux - 1 year ago 170
Javascript Question

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

…using JavaScript only.

I can't found a JS library that can do it.
Is there a completed library or another way (or different logic) to prevent unsafe input?

Answer Source

The best way to do what you are trying to do is by making escapement replacements before parsing the BBCode.

function escape(s) { //
    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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download