Richard Medeiros
Richard Medeiros

Reputation: 978

Placeholder text set by javascript not decoding HTML encoded special characters

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.

Upvotes: 2

Views: 3089

Answers (2)

Walk
Walk

Reputation: 757

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>

Upvotes: 2

RainingChain
RainingChain

Reputation: 7782

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";

Upvotes: 4

Related Questions