Skip to content

Instantly share code, notes, and snippets.

@yukioc
Created January 30, 2011 14:23
Show Gist options
  • Save yukioc/802888 to your computer and use it in GitHub Desktop.
Save yukioc/802888 to your computer and use it in GitHub Desktop.
escape the special characters to HTML entities.
<html>
<style type='text/css'>
* { font-size:small; margin:0; padding:0; }
body { margin: 5px; }
h1{ margin: 5px 0; }
pre { border: 1px solid black; padding: 5px; }
</style>
<body>
<h1>escapeHTML</h1>
<!-- original -->
<h3>original <input type='button' value='update' onclick='run();'</input></h3>
<form><textarea id='org' rows='10' cols='60'>
#include <stdio.h>
int main(int argc,char** argv){
printf("hello\n");
return 0;
}
</textarea></form>
<!-- escapeHTML -->
<h3>escapeHTML</h3>
<form><textarea id='esc' rows='10' cols='60'>
</textarea></form>
<!-- pre -->
<h3>pre</h3>
<pre id='pre'>
</pre>
<script>
function escape_html(str) {
return str.replace(/[&"<>]/g, function(c) {
return {
"&": "&amp;", '"': "&quot;",
"<": "&lt;", ">": "&gt;"
}[c];
});
}
var org = document.getElementById('org');
var esc = document.getElementById('esc');
var pre = document.getElementById('pre');
function run(){
pre.innerHTML = esc.value = escape_html(org.value);
}
run();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment