最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

asp.net - How to HttpUtility.HtmlDecode in javascript - Stack Overflow

programmeradmin3浏览0评论

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 need to set the value of this string into an Option of a drop-down control, replacing the no-break space entity with empty spaces (in order to align with other options).

In the code behind of ASP.NET I would use HttpUtility.HtmlDecode. But how do you decode this string in the 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 need to set the value of this string into an Option of a drop-down control, replacing the no-break space entity with empty spaces (in order to align with other options).

In the code behind of ASP.NET I would use HttpUtility.HtmlDecode. But how do you decode this string in the javascript?

Share Improve this question asked Nov 29, 2015 at 1:08 HidalgoHidalgo 9412 gold badges14 silver badges41 bronze badges 1
  • Possible duplicate of HTML Entity Decode – jacmkno Commented Nov 29, 2015 at 1:32
Add a ment  | 

3 Answers 3

Reset to default 4

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).

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 time
  var element = document.createElement('div');

  function decodeHTMLEntities (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/LYteC/4/

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

theHtml = $.parseHTML( "ABC&nbsp;&nbsp;&nbsp;&nbsp;ABC Description" );
发布评论

评论列表(0)

  1. 暂无评论