Skip to content Skip to sidebar Skip to footer

How To Httputility.htmldecode In Javascript

I have a localStorage holding a string that looks like the follows: 'ABC&nbps;&nbps;&nbps;&nbps;ABC Description' I get this string from the localStorage and I ne

Solution 1:

You can use the following bit of code to convert HTML to text (using just javascript)

var span = document.createElement("SPAN");
 span.innerHTML = "ABC    ABC Description";
 alert(span.innerText);

It creates a dummy element, sets its HTML to your HTML and extracts the text.

Note that it should be nbsp (non-breaking space) and not nbps


That said, the way you are doing this suggests that you are allowing the user to enter arbitrary HTML. This is not a good idea in terms of security (a user could put in malicious HTML into this field).

Solution 2:

This was answered before here. But it's   not &nbps;. To decode wrong markup with &nbps; on it, you will have to do a manual replace: whatever.replace('&nbps;', ' ');

It's safer to strip script tags instead of having the browser parse the raw HTML. That will prevent malicious code from being executed...

var decodeEntities = (function() {
  // this prevents any overhead from creating the object each timevar element = document.createElement('div');

  functiondecodeHTMLEntities (str) {
    if(str && typeof str === 'string') {
      // strip script/html tags
      str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
      str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
      element.innerHTML = str;
      str = element.textContent;
      element.textContent = '';
    }

    return str;
  }

  return decodeHTMLEntities;
})();

http://jsfiddle.net/LYteC/4/

Solution 3:

If you are using Jquery on the client side use this to convert into html.

theHtml = $.parseHTML( "ABC&nbsp;&nbsp;&nbsp;&nbsp;ABC Description" );

Post a Comment for "How To Httputility.htmldecode In Javascript"