Reputation: 3265
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
Upvotes: 2
Views: 3704
Reputation: 26434
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 & Penguins');
=> "Zebras, Elephants & Penguins"
Upvotes: 3