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!
2 Answers
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("&", "&").replace(/(<?)([^<>]*)(>?)/g, function (a,b,c,d) {
if ((b+c+d).toLowerCase() === "<br>") return "<br>";
if (b === "<") b = "<";
if (b === ">") b = ">";
if (d === "<") d = "<";
if (d === ">") d = ">";
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
5 Comments
Martina
tha fact is that in the string I must have the tag <br>
SReject
Is that the only character you need?
SReject
if the userinput uses carriage return/newline feeds instead of
<br>, use the above.SReject
Updated my answer so
<br> tags are preserved.Martina
thank you! later I will try and I can give you the correct answer
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
Quentin
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.Martina
tha fact is that in the string I must have the tag <br>
Quentin
@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.
document.createTextNode('some string')