Wednesday 20 October 2021

Javascript Decode encoded html entities in a JSON object into decoded ones

https://gomakethings.com/decoding-html-entities-with-vanilla-javascript/ 


HTML entities such as <p>In this course, you'll learn:</p> is usally encoded in JSON string as 

&lt;p&gt;In this course, you&amp;rsquo;ll learn:&lt;/p&gt; to avoid quots "" errors in JSON string



To decode HTML entites (to get <p>) back in JS so that it is properly shown in a web page(If do not decode HTML entities browser will show HTML tag <p> as text instead of having any effects),


we will need to utlize textarea, as getting values in text area will automatically be converted into decoded HTML entities


// Create globally used textarea

var domTextArea =  document.createElement('textarea');


// Function that takes a JSON object, and recursively decode encoded HTML entities if needed        

decodeHTML(testObj) {

   

            for (var key in testObj) {

                if (typeof (testObj[key]) == 'string') {

                    domTextArea.innerHTML = testObj[key];

                    testObj[key] = this.domTextArea.value;

                    continue;

                }


                this.decodeHTML(testObj[key]);


            };

        },



NOTE: for (var key in testObj) will also work for array :


var a = [1,2,3];


for (var key in a) { console.log(a[key]) }

// Output:

 1

2

 3


No comments:

Post a Comment