Replace HTML special characters to Text special characters

I have a table and I am inserting the data to the table using jquery, But when I sending data to server for validation the html characters like '&' are coming like & amp;. So for this purpose I made two methods just to convert html characters back to the text characters.

Method 1:

function decodeHtml(str) {
    var map =
        '&': '&',
        '&lt;': '<',
        '&gt;': '>',
        '&quot;': '"',
        '&#039;': "'"
return str.replace(/&amp;|&lt;|&gt;|&quot;|&#039;/g, function (m) { return map[m];


Method 2 :

function decodeHTML(str){ 
    return $('<div>').html(str).text(); 

So, my question is that which method is best and why?

Answers 1

  • The second method uses 1. chaining. 2. jquery performs a lot of checks while executing a function. 3. accessing DOM.

    It is clear that the first method is faster as it is plain javascript.Though it won't make such huge difference in your scenario but the second method can be really slow if you don't use it wisely because when jQuery builds elements from a string, it adds all top level items by iterating them. So you might need to wrap html in a single item.

    Jquery is faster when accessing DOM with class name, working with arrays, etc.

    Hope, it clarify things!

    P.S. faster not to be confused with better or recommended.

Related Articles