Skip to content

Instantly share code, notes, and snippets.

@bingeboy
Forked from mathiasbynens/unicodeEscape.js
Created July 1, 2013 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bingeboy/5897634 to your computer and use it in GitHub Desktop.
Save bingeboy/5897634 to your computer and use it in GitHub Desktop.
// Ever needed to escape '\n' as '\\n'? This function does that for any character,
// using hex and/or Unicode escape sequences (whichever are shortest).
// Demo: http://mothereff.in/js-escapes
function unicodeEscape(str) {
return str.replace(/[\s\S]/g, function(character) {
var escape = character.charCodeAt().toString(16),
longhand = escape.length > 2;
return '\\' + (longhand ? 'u' : 'x') + ('0000' + escape).slice(longhand ? -4 : -2);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment