How Do I Correctly Insert Unicode In An Html Title Using Javascript?
Solution 1:
JavaScript string constants are parsed by the JavaScript parser. Text inside HTML tags is parsed by the HTML parser. The two languages (and, by extension, their parsers) are different, and in particular they have different ways of representing characters by character code.
Thus, what you've discovered is the way reality actually is :-) Use the \u
escape notation in JavaScript, and use HTML entities (&#nnnn;
) in HTML/XML.
edit — now the situation can get even more confusing when you're talking about creating/inserting HTML from JavaScript. When you use .innerHTML
to update the DOM from JavaScript, then you are basically handing over HTML source code to the HTML parser for interpretation. For that reason, you can use either JavaScript \u
escapes or HTML entities, and things will work (excepting painful issues of character encoding mismatches etc).
Finally, note that JavaScript also provides the String.fromCharCode()
function to construct strings from numeric character codes.
Solution 2:
The best way to work with Unicode characters in JavaScript is to use the characters themselves, using an editor or other tool that can store them in UTF-8 encoding. You will avoid a lot of confusion. Naturally, you need to properly declare the character encoding of your .js or .html file.
The construct 吧
has no special meaning in JavaScript; it is just eight Ascii characters. But if your JavaScript code has been embedded into an HTML document, then it will be processed by HTML rules before passing to the JavaScript interpreter. And the rules vary by HTML version. Yet another reason to avoid such constructs.
So just write
document.title = "吧出";
(Of course, there are very few situations where you should change the title
element content—which is crucial to search engines and many other purposes—in JavaScript, instead of setting it in HTML. But that’s beside the point.)
Post a Comment for "How Do I Correctly Insert Unicode In An Html Title Using Javascript?"