javascript 使用 JS - jQuery,如何取消转义 html 并将`quotes & <>` 放回字符串中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22279231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:49:55  来源:igfitidea点击:

Using JS - jQuery, how can I unescape html and put `quotes & <>` back in the string?

javascriptjqueryescaping

提问by Squirrl

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

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

function escapeHtml(unsafe) {
    return unsafe
         .replace(/&/g, "&amp;")
         .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>"

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

我尝试了显而易见的但没有交易。http://jsfiddle.net/ej6bX/

回答by Arun P Johny

You need to use

你需要使用

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


A more clear approach using jQuery could be

使用 jQuery 的更清晰的方法可能是

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

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

Demo: Fiddle

演示:小提琴

回答by Pranav C Balan

The second parameter of replace()should be string not regular expression

的第二个参数replace()应该是字符串而不是正则表达式

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

Fiddle

Fiddle