本质上,我想撤消我发现的 escapeHTML() 函数 below , 在我使用它之后。
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function unescapeHtml(safe) {
return safe
.replace("&", /&/g)
.replace("<", /</g)
.replace( ">", />/g)
.replace(""", /"/g)
.replace("'", /'/g);
}
var a = escapeHtml("<div> yo & yo squirrl's </div>");
var b = unescapeHtml(a);
console.log(a);
console.log(b);//should log "<div> yo & yo squirrl's </div>"
我尝试了明显但没有效果。 http://jsfiddle.net/ej6bX/
最佳答案
你需要使用
function unescapeHtml(safe) {
return safe.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'");
}
使用 jQuery 的更清晰的方法可能是
function escapeHtml(unsafe) {
return $('<div />').text(unsafe).html()
}
function unescapeHtml(safe) {
return $('<div />').html(safe).text();
}
演示:Fiddle
关于javascript - 使用 JS - jQuery,如何取消转义 html 并将 `quotes & <>` 放回字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22279231/