Skip to content

Instantly share code, notes, and snippets.

@fengxiaochuang
Forked from mathiasbynens/unicodeEscape.js
Created March 3, 2017 04:53
Show Gist options
  • Save fengxiaochuang/9bcf5b580d0f50519f13e2cc458d2492 to your computer and use it in GitHub Desktop.
Save fengxiaochuang/9bcf5b580d0f50519f13e2cc458d2492 to your computer and use it in GitHub Desktop.
Escape all characters in a string using both Unicode and hexadecimal escape sequences
// 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);
});
}
@fengxiaochuang
Copy link
Author

fengxiaochuang commented Mar 3, 2017

function escapeUnicode(str) {
    if (str instanceof Object) {
        str = JSON.stringify(str);
    }
    return str.replace(/[^\0-~]/g, function (ch) {
        return "\\u" + ("000" + ch.charCodeAt().toString(16)).slice(-4);
    });
}

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