简体   繁体   中英

How to pass accented characters from JavaScript to HTML?

In JavaScript I create a string which has accented characters such as 'ò' or 'à', eg "ò à"

I seem to be unable to create text nodes in html which show the accented characters: if i pass them directly, i get "white question mark in black rhombus"; if i replace the accented characters by the corresponding html entities, i get the entities printed verbatim.
This function

function showAccents() {
  s1="ò à";
  s2 = s1.replace(/ò/, "ò").replace(/à/, "&agrave");;
  var eD = document.getElementById("accent1");
  var eHT1 = document.createTextNode(s1);
  var eHT2 = document.createTextNode(s2);
  eD.appendChild(eHT1);
  eD.appendChild(eHT2);
}

Produces the following text:

ò &agrave

How do I have to convert the string to get accented characters in HTML?

You are probably missing a page encoding. Make sure your HTML includes either this:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

Or this (HTML5):

<meta charset="utf-8">

EDIT

It now seems that the problem is the encoding of your Javascript file. It too needs to be Unicode (encoded as UTF8 for example), as if it is saved in a non-Unicode encoding you are likely to have ò and à misinterpreted by the browser which might read these with a different encoding. Just open it in a text editor and save it as UTF8 (doing so will include a BOM at the start of the file that will specify its encoding, solving the problem)

It turned out my xemacs encodes with ISO-8859-1; the current version can not be easily set to UTF-8.

The solution was to change the encoding info from "utf-8" to "iso-8859-1" in the xhtml's header:

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>  
  <meta name="http-equiv" content="Content-type: text/html; charset=ISO-88591"/>

  <script type="text/javascript" src="js/conjutils.js" charset="iso-8859-1" />
  <script type="text/javascript" src="js/xmlutils.js" charset="iso-8859-1" />
  <link rel="stylesheet" type="text/css" href="css/conjugation.css" />    
  <title>Conjugation</title>

</head>

Now i can set a string to 'àò' in my js file, and the browser will display it correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM