Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
90
rated 0 times [  96] [ 6]  / answers: 1 / hits: 155379  / 11 Years ago, tue, december 31, 2013, 12:00:00

Assume I have a page with an input box. The user types something into the input box and hits a button. The button triggers a function that picks up the value typed into the text box and outputs it onto the page beneath the text box for whatever reason.



Now this has been disturbingly difficult to find a definitive answer on or I wouldn't be asking but how would you go about outputting this string:



<script>alert(hello)</script> <h1> Hello World </h1>


So that neither the script is executed nor the HTML element is displayed?



What I'm really asking here is if there is a standard method of avoiding both HTML and Script injection in Javascript. Everyone seems to have a different way of doing it (I'm using jQuery so I know I can simply output the string to the text element rather than the html element for instance, that's not the point though).


More From » html

 Answers
20

You can encode the < and > to their HTML equivelant.



html = html.replace(/</g, &lt;).replace(/>/g, &gt;);


How to display HTML tags as plain text


[#73474] Sunday, December 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jonrened

Total Points: 627
Total Questions: 114
Total Answers: 99

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
jonrened questions
Mon, Nov 2, 20, 00:00, 4 Years ago
Tue, May 19, 20, 00:00, 4 Years ago
Tue, Jan 21, 20, 00:00, 4 Years ago
Thu, Nov 7, 19, 00:00, 5 Years ago
;