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!

3
  • Have a look at this question: stackoverflow.com/questions/5499078/… Commented Nov 12, 2012 at 17:07
  • Simple solution: Don't use innerHTML. document.createTextNode('some string') Commented Nov 12, 2012 at 17:09
  • and this works with the tag <br> ? Commented Nov 12, 2012 at 17:13

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

5 Comments

tha fact is that in the string I must have the tag <br>
Is that the only character you need?
if the userinput uses carriage return/newline feeds instead of <br>, use the above.
Updated my answer so <br> tags are preserved.
thank you! later I will try and I can give you the correct answer
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.

3 Comments

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.
tha fact is that in the string I must have the tag <br>
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.