2

Is there a javascript function that recognize if a string variable contains HTML code? I would like to avoid this case because if I use innerHTML and the user has submitted something like <img src='link'> it doesn't appear the string but the real image... I hope I explained Thank you!

Shmiddty
  • 13,847
  • 1
  • 35
  • 52
Martina
  • 1,852
  • 8
  • 41
  • 78

2 Answers2

2

You can just replace 3 very special characters:
&: used for glyph notation
<: opening bracket for html tags
>: closeing bracket for html tags

function make_safe(input) {
    return input.replace("&", "&amp;").replace(/(<?)([^<>]*)(>?)/g, function (a,b,c,d) {
        if ((b+c+d).toLowerCase() === "<br>") return "<br>";

        if (b === "<") b = "&lt;";
        if (b === ">") b = "&gt;";

        if (d === "<") d = "&lt;";
        if (d === ">") d = "&gt;";

        return b+c+d;
    }).replace(/\r?\n/g,"<br>");
}

// example:
mydiv.innerHTML = make_safe('<img src="/pic.jpg">');



I did a little magic so \r\n becomes a newline, and <br> tags are preserved

SReject
  • 3,774
  • 1
  • 25
  • 41
1

Not really. Telling the difference between HTML and text talking about HTML is not a trivial problem.

If you are expecting text input, then deal with text not HTML. Don't use innerHTML, use createTextNode and appendChild/insertBefore.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • `createTextNode` gives no special meaning to the `<` or `>` characters at all. It takes a string and treats it as plain text to be added to the DOM, not HTML that needs to be parsed. – Quentin Nov 12 '12 at 17:13
  • tha fact is that in the string I must have the tag
    – Martina Nov 12 '12 at 17:14
  • @Marty – So you want *some* HTML to be escaped and *some* HTML to be passed through? That is a different and much, much more complicated problem. – Quentin Nov 12 '12 at 17:16