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
  • 898
  • 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
  • 6,887
  • 9
  • 31
  • 66
1

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,132
  • 1
  • 14
  • 24
Walk
  • 707
  • 4
  • 14