Skip to content

Instantly share code, notes, and snippets.

@thomasfl
Created October 14, 2011 08:03
Show Gist options
  • Save thomasfl/1286520 to your computer and use it in GitHub Desktop.
Save thomasfl/1286520 to your computer and use it in GitHub Desktop.
Escape unsafe characters in javascript.
/*
* Convert unicode characters to safe characters.
*
* Usage:
* $ node
* > var utf8 = require("./escape_utf8.js");
* > utf8.unicodeEscapeChars("This is a test with æøå and ÆØÅ");
* 'This is a test with \\xe6\\xf8\\xe5 and \\xc6\\xd8\\xc5'
*/
exports.unicodeEscapeChars = function(str) {
var code, pref = {1: '\\x0', 2: '\\x', 3: '\\u0', 4: '\\u'};
var escaped = str.replace(/\W/g, function(c) {
return (pref[(code = c.charCodeAt(0).toString(16)).length] + code);
});
return escaped.replace(/\\x20/g," ");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment