Encode HTML entities

2019-02-23 16:57发布

I am parsing some data from feedburner of which contains HTML entities. I am trying to encode the HTML entities using jQuery as such:

var encodedStr = data['1']['result']['content']; // content with HTML entities
$("#content").html(encodedStr).text();

but with no results.

Here is what its parsed: http://jsbin.com/ihadam/1/edit

2条回答
再贱就再见
2楼-- · 2019-02-23 17:17

Basically you should encode your html entities into html as such:

var encodedStr = data['1']['result']['content'];
var a = $("#content").html(encodedStr).text();

Then get the encoded text and apply it as html() as such:

$("#content").html(a);

That should work.

Demo: http://jsbin.com/ihadam/9/edit

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-02-23 17:26

You can save the bloat of JQuery with pure JavaScript functions.

Sometimes you just want to encode every character... This function replaces "everything except for nothing" in regxp.

function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}

function encode(w) {
  return w.replace(/[^]/g, function(w) {
    return "&#" + w.charCodeAt(0) + ";";
  });
}

test.value=encode(document.body.innerHTML.trim());
<textarea id=test rows=11 cols=55>www.WHAK.com</textarea>

查看更多
登录 后发表回答