Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a list of unicode characters in a for loop

I am trying to list use the counter in a for loop as the number of a unicode character. The purpose of this, ...lets just say I am doing it for fun. Surely, a seasoned javascript user will be able to tell me what is wrong here.

To use a unicode character in javascript one can either type it in as it is, or use an escape sequence like: \u8211. My problem arises when I try to combine the number part with the escaped u. The error I get is something along the lines of "bad escape character", and it means that the number from the i variable is not combined with the \u as I'm hoping for.

for (var i=65; i< 90; i++ ) {                                          
    anchor = document.createElement('a'),
    img = document.createElement('img'),
    character = "\\u"+i;
    img.setAttribute('alt', character);
    img.setAttribute('src', '');

    anchor.appendChild(document.createTextNode(i +": "));
    anchor.appendChild(img);

    anchor.setAttribute('title', character);
    body.appendChild(anchor);
    body.appendChild(document.createElement('br'));
}

What I have tried:

character = "\u{"+i+"}"

cha = ['\\u'];
cha.push(i);
cha.join('');

... and i've run out of ideas

An example:

jsfiddle.net/Dn4Vv/

like image 612
Ярослав Рахматуллин Avatar asked Oct 05 '12 12:10

Ярослав Рахматуллин


1 Answers

The biggest problem is that \uXXXX is interpreted at the time that the code is parsed; just as you can't write '"' + '"' to mean the same as "" (because " is an actual double-quote in the code, whereas '"' is a string containing "), you can't write '\\u' + 'XXXX' to mean the same as '\uXXXX'.

As Brad Christie says in a comment above, you should use the function String.fromCharCode to convert from an integer to the character you need:

    character = String.fromCharCode(i);

A second problem — this is academic, due to the above, but I think I should mention it — is that the \uXXXX notation expects the character code to be given in hexadecimal notation, and zero-padded to exactly four hexadecimal digits, whereas you're giving it in decimal notation, and without zero-padding. For example, you're writing \u65, but the Unicode-escape syntax for A is actually \u0041.

like image 134
ruakh Avatar answered Sep 18 '22 23:09

ruakh