Skip to content

Instantly share code, notes, and snippets.

@mathiasbynens
Created September 26, 2011 19:50

Revisions

  1. mathiasbynens revised this gist Dec 22, 2011. 1 changed file with 8 additions and 5 deletions.
    13 changes: 8 additions & 5 deletions unicodeEscape.js
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,10 @@
    // Ever needed to escape '\n' as '\\n'? This function does that for any character, using its Unicode code point.
    // https://github.com/mathiasbynens/mothereffingcssescapes/blob/46799d70e9d18d02151db8b470880ee3d0873832/eff.js#L63-64
    // 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.split('').map(function(character) {
    return '\\u' + ('0000' + character.charCodeAt().toString(16)).slice(-4);
    }).join('');
    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);
    });
    }
  2. mathiasbynens revised this gist Sep 27, 2011. 1 changed file with 2 additions and 3 deletions.
    5 changes: 2 additions & 3 deletions unicodeEscape.js
    Original file line number Diff line number Diff line change
    @@ -1,8 +1,7 @@
    // Ever needed to escape '\n' as '\\n'? This function does that for any character, using its Unicode code point.
    // https://github.com/mathiasbynens/mothereffingcssescapes/blob/46799d70e9d18d02151db8b470880ee3d0873832/eff.js#L63-64
    function unicodeEscape(str) {
    return str.split('').map(function(char) {
    char = char.charCodeAt().toString(16);
    return '\\u' + '0000'.slice(0, 4 - char.length) + char;
    return str.split('').map(function(character) {
    return '\\u' + ('0000' + character.charCodeAt().toString(16)).slice(-4);
    }).join('');
    }
  3. mathiasbynens created this gist Sep 26, 2011.
    8 changes: 8 additions & 0 deletions unicodeEscape.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    // Ever needed to escape '\n' as '\\n'? This function does that for any character, using its Unicode code point.
    // https://github.com/mathiasbynens/mothereffingcssescapes/blob/46799d70e9d18d02151db8b470880ee3d0873832/eff.js#L63-64
    function unicodeEscape(str) {
    return str.split('').map(function(char) {
    char = char.charCodeAt().toString(16);
    return '\\u' + '0000'.slice(0, 4 - char.length) + char;
    }).join('');
    }