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!
Asked
Active
Viewed 1,557 times
2
2 Answers
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("&", "&").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

SReject
- 3,774
- 1
- 25
- 41
-
-
-
if the userinput uses carriage return/newline feeds instead of `
`, use the above. – SReject Nov 12 '12 at 17:18 -
-
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
-
-
@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
? – Martina Nov 12 '12 at 17:13