Home > Enterprise >  Using &letter; notation in JavaScript doesn't write greek letters
Using &letter; notation in JavaScript doesn't write greek letters

Time:01-29

When I set an input box value with the "value" attribute in HTML to a greek letter, it shows the greek letter correctly. But when I change the "value" attribute with JavaScript, it uses the "&letter;" format. What can I do so that JavaScript behaves just as HTML?

HTML: <input type="text" id="input" value = "&epsilon;"> works fine. JavaScript: document.getElementById("input").value = "&epsilon;"; shows &epsilon; but not the greek letter

CodePudding user response:

The problem you're facing occurs because of the way you're setting the input. Javascript is (correctly) treating your &epsilon; as an ordinary string, because you haven't told it that it's anything else.

If this were an element like p, or span or any other contextual text element, you could simply do

myElem.innerHTML = "&epsilon;";

However, since you want to set this to be the input's value, you can't use innerHTML, because it wouldn't make any sense. What you need to do is something like this.

function htmlDecode(input) {
  var doc = new DOMParser().parseFromString(input, "text/html");
  return doc.documentElement.textContent;
}

document.getElementById("myInput").value = htmlDecode("&epsilon;");
<input type="text" id="myInput" name="myInput" value="">

The function I used was originally posted in this SO answer. Be sure to read the rest of it, to see the other uses.

  • Related