This is the source of my simple HTML page (save as .html file):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function convert(){
var ele1 = document.getElementById("somewhere");
var replaced;
replaced = ele1.value;
replaced = replaced.replace(/&/ig, "&");
replaced = replaced.replace(/</ig, "<");
replaced = replaced.replace(/>/ig, ">");
replaced = replaced.replace(/'/ig, "'");
replaced = replaced.replace(/"/ig, """);
ele1.value = replaced;
}
</script>
</head>
<body>
<textarea cols="70" id="somewhere" rows="15" style="background: none repeat scroll 0% 0% rgb(250, 250, 250); border: 2px solid rgb(204, 204, 204);"></textarea><br />
<input onclick="convert();" type="button" value="Encode" />
</body>
</html>
What this page does is, any code put in the textarea is HTML-encoded/escaped when the “Encode” button is clicked — essentially all instances of &, <, >, ' and " in the input code are replaced with their respective HTML entities.
How do I modify the JavaScript code in the page, so that only the input code between <pre> and </pre> tags is modified as aforementioned?
EDIT: As I see it I wasn’t clear. First you need to save the HTML code I gave above into a .html file and open it in a browser. Then you will see a textarea/textbox with an “Encode” button below it.
Any code put into the text area is escaped when the “Encode” button is pressed.
I want to modify the JavaScript code in the HTML code above, so that (for instance) if I put the following code in the textbox:
It's mine.
<pre>
<input onclick="convert();" type="button" value="Encode" />
</pre>
It's also mine.
and hit the “Encode” button, only the code between <pre> tags is escaped. I hope I am clear this time.
Hope I am clear, and can get some help. Thanks.
Insead of using:
You could use:
However this might return multiple elements since there could be multiple
<pre>sections in your html.But again, if your goal is to produce a safe output, escaping is not a preferred solution. Have a look at Markdown for example:
http://daringfireball.net/projects/markdown/basics