2

When setting placeholder text via javascript, special characters are not displaying properly.

function myFunction() {
    document.getElementById("myText").placeholder = "Événement";
}
<input type="text" id="myText" placeholder="&#201;v&#233;nement">

<p>Click the button to change the placeholder text of the text field.</p>

<button onclick="myFunction()">Try it</button>

Output is: "&#201;v&#233;nement"

Expected output: "Événement"

Looking for a javascript solution where I can convert any text containing any encoded character.

Richard Medeiros
  • 938
  • 9
  • 18

2 Answers2

4

In HTML, special characters are encoded with &#XXX (Like &#201).

In Javascript, special characters are encoded with \uXXXX (Like \u00C9)

Check https://en.wikipedia.org/wiki/List_of_Unicode_characters for the list of escape code.

In your case, it would be

document.getElementById("myText").placeholder = "\u00C9v\u00E8nement";

RainingChain
  • 7,397
  • 10
  • 36
  • 68
2

The most straightforward way to convert is to create an element, set your HTML entity as innerHTML and get textContent, something like this:

function myFunction() {
  let a = document.createElement('span');
  a.innerHTML = '&#201;v&#233;nement from JS';
  document.getElementById("myText").placeholder = a.textContent;
}
<input type="text" id="myText" placeholder="&#201;v&#233;nement">

<p>Click the button to change the placeholder text of the text field.</p>

<button onclick="myFunction()">Try it</button>
Scott Martin
  • 1,260
  • 2
  • 17
  • 27
Walk
  • 737
  • 4
  • 15