Skip to content

Instantly share code, notes, and snippets.

@JavaScript-Packer
Created August 21, 2015 14:06
Show Gist options
  • Select an option

  • Save JavaScript-Packer/21328771e1e1cab4d017 to your computer and use it in GitHub Desktop.

Select an option

Save JavaScript-Packer/21328771e1e1cab4d017 to your computer and use it in GitHub Desktop.
Only encode codepoints 127 and up. 127 to 255 get encoded to hexdecimal and 256 to 65536 get encoded to unicode
String.prototype.replaceWithUtf8 = function() {
function r(r) {
for (var t, n, e = "", i = 0; !isNaN(t = r.charCodeAt(i++)); ) n = t.toString(16),
e += 256 > t ? "\\x" + (t > 15 ? "" :"0") + n :"\\u" + ("0000" + n).slice(-4);
return e;
}
var a, c, o, u, s, e = "", i = this, t = [ "/", '"' ], n = [ "\\/", '\\"' ];
for (a = 0; a < i.length; a++) c = i.charCodeAt(a), o = i.charAt(a), u = t.indexOf(o),
u > -1 ? e += n[u] :c > 126 && 65536 > c ? (s = r(o), e += s) :e += o;
return e;
};
@JavaScript-Packer

Copy link
Copy Markdown
Author

USAGE:

alert("Lärm, Lichter, Lücken, Löcher.".replaceWithUtf8());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment