Unescaping ampersand characters in javascript

喜你入骨 提交于 2019-12-05 09:19:54

You need to decode them like this:

$('#myText').val($("<div/>").html(str).text());

Demo: http://jsfiddle.net/QUbmK/

You can move the decode part to function too and call that instead:

function jDecode(str) {
    return $("<div/>").html(str).text();
}

$('#myText').val(jDecode(str));

First off, you can't run the code you have in your example. document.body is not ready for manipulation in the HEAD tag. You have to run that after the document has loaded. If I put your code in a safe place to run, it works fine as you can see here.

So ... there must be more to your situation than the simple example you show here. You can see your simple example works fine here when the code is put in the right place:

http://jsfiddle.net/jfriend00/RDSNz/

Mark Kahn

That doesn't happen, at least not with jQuery. If you do, literally: $(document.body).html('&lt;div&gt;'), you will get <div> printed to the screen, not a div tag. If you're doing something not listed in your question:

either use .text() instead of .html() or replace all & with &amp;:

$(document.body).text(str);
$(document.body).html(str.replace(/&/g, '&amp;'))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!