Skip to content

Instantly share code, notes, and snippets.

@mayuki
Created May 31, 2010 07:41
Show Gist options
  • Select an option

  • Save mayuki/419631 to your computer and use it in GitHub Desktop.

Select an option

Save mayuki/419631 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<meta charset="UTF-8">
<title>JavaScript 文字列エスケープ</title>
<style>
textarea { width: 100%; }
.buttonArea { text-align:center }
</style>
<h1>JavaScript 文字列エスケープ</h1>
<div>
<textarea id="input" cols="60" rows="20">
</textarea>
</div>
<div class="buttonArea">
<input type="button" onclick="escape()" value="↓Escape">
</div>
<div>
<textarea id="output" cols="60" rows="20">
</textarea>
<!--input type="button" onclick="alert(eval(document.getElementById('output').value));" value="View"-->
</div>
<script>
function escape() {
var t = document.getElementById('input');
document.getElementById('output').value = '"' +
t.value
.replace(/\\/g, "\\\\")
.replace(/"/g, "\\\"")
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r")
.replace(/\t/g, "\\t")
.replace(/(<\/sc)(ript>)/, "$1\" + \"$2")
.replace(/[^\x00-\x7f]/g, function($0) { return escapeUnicode($0); })
+ '"';
}
function escapeUnicode(str) {
return str.replace(/[^ -~]|\\/g, function(m0) {
var code = m0.charCodeAt(0);
return '\\u' + ((code < 0x10) ? '000' :
(code < 0x100) ? '00' :
(code < 0x1000) ? '0' : '') + code.toString(16);
});
}
function unescapeUnicode(str) {
return str.replace(/\\u([a-fA-F0-9]{4})/g, function(m0, m1) {
return String.fromCharCode(parseInt(m1, 16));
});
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment