Created
October 14, 2011 08:03
-
-
Save thomasfl/1286520 to your computer and use it in GitHub Desktop.
Escape unsafe characters in javascript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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