|
<!DOCTYPE html> |
|
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> |
|
<h1> |
|
<input id="i0" name="lang" onclick="refresh()" type="radio" checked><label for="i0" title="\u00FF only">Java String Encoder</label><br> |
|
<input id="i1" name="lang" onclick="refresh()" type="radio"><label for="i1" title="\xFF and \u0100">JavaScript String Encoder</label> |
|
</h1> |
|
<textarea onkeyup="refresh()" rows="8" cols="100">// Paste some Java or JavaScript code into this window. |
|
german = "Übergröße"; |
|
smilie = "☺";</textarea> |
|
<pre onclick="select(this)">This encoding utility requires JavaScript.</pre> |
|
<script type="text/javascript"> |
|
// 127 bytes |
|
var encodeJavaScriptString = function f(a, b) |
|
{ |
|
return ++b //`b` is a number (including 0) when `replace` calls the function |
|
? '\\' + ( //all escape sequences start with a backslash |
|
(a = a.charCodeAt()) >> 12 //all characters from U+1000 and above |
|
? 'u' //must start with `\u` |
|
: a >> 8 //all characters from U+0100 to U+0FFF |
|
? 'u0' //must start with `\u0` |
|
: 'x' //characters from U+007F to U+00FF can start with `\u00` or `\x` |
|
) + a.toString(16).toUpperCase() //add the upper case hex string (it does not contain leading zeros) |
|
: a.replace(/[^\0-~]/g, f) //else call the function for all non-ASCII characters (all except U+0000 to U+007E) |
|
} |
|
// 115 bytes |
|
var encodeJavaString = function e(a, b) |
|
{ |
|
return ++b //`b` is a number when `replace` calls the function |
|
? '\\u' + //in Java all escape sequences must start with `\u` |
|
('00' + a.charCodeAt().toString(16)) //build a hex string with at least 4 characters |
|
.slice(-4).toUpperCase() //use the last 4 characters and make them upper case |
|
: a.replace(/[^\0-~]/g, e) //else call the function for all non-ASCII characters (all except U+0000 to U+007E) |
|
} |
|
// 89 bytes |
|
var select = function(a, b) |
|
{ |
|
b = document.createRange(); |
|
b.selectNode(a); |
|
window.getSelection().addRange(b) |
|
} |
|
var refresh = function() |
|
{ |
|
var t = document.getElementsByTagName('TEXTAREA')[0]; |
|
var p = document.getElementsByTagName('PRE')[0]; |
|
var f = document.getElementById('i1').checked ? encodeJavaScriptString : encodeJavaString; |
|
p.firstChild.data = f(t.value).replace(/\r\n/g, '\n'); |
|
} |
|
refresh(); |
|
</script> |
I know. Even if it's possible, such characters should never appear in source code files. What we can do is replacing
\t
with\0
to avoid bad conversions. But I'm not sure if this works in all browsers. Added it to my tests suite.