2

I have a string javascript message like this one :

var message = "merci d'ajouter";

And I want this text to be converted into this one (decoding) :

var result = "merci d'ajouter";

I don't want any replace method, i want a general javascript solution working for every caracter encoded. Thanks in advance

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
Mehdi Souregi
  • 3,153
  • 5
  • 36
  • 53
  • 4
    Possible duplicate of [HTML Entity Decode](http://stackoverflow.com/questions/5796718/html-entity-decode) – I wrestled a bear once. Jun 22 '16 at 15:10
  • 2
    It seems to me that any "general JavaScript" solution would involve replacement. This is like asking for a shirt to be made but use no stitching. On the other hand, decoding can be handled by the browser when setting the character type in the header. – durbnpoisn Jun 22 '16 at 15:11

1 Answers1

3

This is actually possible in native JavaScript

Heep in mind that IE8 and earlier do not support textContent, so we will have to use innerText for them.

function decode(string) {
    var div = document.createElement("div");
    div.innerHTML = string; 
    return typeof div.textContent !== 'undefined' ? div.textContent : div.innerText;
}

var testString = document.getElementById("test-string");
var decodeButton = document.getElementById("decode-button");
var decodedString = document.getElementById("decoded-string");
var encodedString = "merci d'ajouter";
      
decodeButton.addEventListener("click", function() {
  decodedString.innerHTML = decode(encodedString); 
});
<h1>Decode this html</h1>
<p id="test-string"></p>
<input type=button id="decode-button" value="Decode HTML"/>
<p id="decoded-string"></p>

An easier solution would be to use the Underscore.js library. This is a fantastic library that provides you with a lot of additional functionality.

Underscore provides an _unescape(string) function

The opposite of escape, replaces &, <, >, ", ` and ' with their unescaped counterparts.

_.unescape('Zebras, Elephants &amp; Penguins');
=> "Zebras, Elephants & Penguins"
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87