Search code examples
javascriptunicode

Javascript: Invalid Unicode escape sequence while storing accessing unicode


I am setting Fontawesome Icon codes in SELECT box and accessing on change event. On accessing I am getting error:

Invalid Unicode escape sequence

Code given below:

HTML

<select name="faicons" id="faicons" class="form-control selectpicker">
    <option value="0">Select</option>
    <option value="uF26E" class="fa fa-500px"> 500px</option>
    <option value="uF26E" class="fa fa-linkedin"> LinkedIn</option>
</select>

Javascript

function renderIcon(code) {
    var context = null;
    code = "F26E"
    var icon_code = "\u"+code;
    context = main_canvas.getContext('2d');
    context.font='32px FontAwesome';
    context.fillText(icon_code,20,75);
    context.fillText("My TEXT!", 140, 90);
}

Solution

  • Unicode escape sequences are only recognized if they're fully contained in a single string literal. Concatenating parts of an escape sequence won't work. To create a character string from a code point dynamically, try String.fromCodePoint. This function takes the code point as a number, not a string though.

    // works
    console.log("\u0041");
    
    // doesn't work
    try {
      eval('console.log("\\u" + "0041");');
    }
    catch (e) {
      console.log(e.message);
    }
    
    // works, but takes a number
    console.log(String.fromCodePoint(0x0041));
    
    // works, but not recommended
    console.log(eval("'\\u" + "0041" + "'"));
    
    // works with a string
    console.log(String.fromCodePoint(parseInt("0041", 16)));