使用JS - jQuery,我如何解开html并把`quote& <>`回到字符串? [英] Using JS - jQuery, how can I unescape html and put `quotes & <>` back in the string?

查看:96
本文介绍了使用JS - jQuery,我如何解开html并把`quote& <>`回到字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本质上,我想撤消escapeHTML()函数,我发现下面,在我使用它之后。

Essentially I want to undo the escapeHTML() function I found below, after I used it.

function escapeHtml(unsafe) {
    return unsafe
         .replace(/&/g, "&")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
 }

function unescapeHtml(safe) {
    return safe
         .replace("&amp;", /&/g)
         .replace("&lt;", /</g)
         .replace( "&gt;", />/g)
         .replace("&quot;", /"/g)
         .replace("&#039;", /'/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/

I tried the obvious but no deal. http://jsfiddle.net/ej6bX/

推荐答案

您需要使用

function unescapeHtml(safe) {
    return safe.replace(/&amp;/g, '&')
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&quot;/g, '"')
        .replace(/&#039;/g, "'");
}






使用jQuery的更清晰的方法be


A more clear approach using jQuery could be

function escapeHtml(unsafe) {
    return $('<div />').text(unsafe).html()
}

function unescapeHtml(safe) {
    return $('<div />').html(safe).text();
}

演示:小提琴

这篇关于使用JS - jQuery,我如何解开html并把`quote&amp; &lt;&gt;`回到字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆