I am trying to list use the counter in a for loop as the number of a Unicode character.
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:
body = document.getElementsByTagName('body')[0];
anchor = document.createElement('a');
img = document.createElement('img');
character = "\u8211";
img.setAttribute('alt', character);
img.setAttribute('src', '');
anchor.appendChild(document.createTextNode("x : "));
anchor.appendChild(img);
anchor.setAttribute('title', character);
body.appendChild(anchor);
body.appendChild(document.createElement('br'));
for (var i = 65; i < 87; i++) {
anchor = document.createElement('a');
img = document.createElement('img');
character = "\\u" + i;
//character = "\u" + i; << bad unicode escape
img.setAttribute('alt', character);
img.setAttribute('src', '');
console.log(img);
anchor.appendChild(document.createTextNode(i + ": "));
anchor.appendChild(img);
anchor.setAttribute('title', character);
body.appendChild(anchor);
body.appendChild(document.createElement('br'));
//console.log( tosay.join(''));
}
body {
font-size: 12px;
font-face: monotype;
}
<html>
<head>
<title>UTF chars</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
</body>
</html>
The biggest problem is that
\uXXXXis 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.fromCharCodeto convert from an integer to the character you need:A second problem — this is academic, due to the above, but I think I should mention it — is that the
\uXXXXnotation 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 forAis actually\u0041.