How do I correctly insert unicode in an HTML title using JavaScript?

前端 未结 2 1704
孤独总比滥情好
孤独总比滥情好 2020-12-16 02:15

I\'m seeing some weird behavior when I\'m setting the title of an HTML page using JavaScript. If I insert html character references directly into the title the Unicode rend

2条回答
  •  独厮守ぢ
    2020-12-16 02:27

    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.

提交回复
热议问题