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

会有一股神秘感。 提交于 2019-12-29 08:46:10

问题


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

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/


回答1:


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

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

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

Demo: Fiddle




回答2:


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

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

Fiddle



来源:https://stackoverflow.com/questions/22279231/using-js-jquery-how-can-i-unescape-html-and-put-quotes-back-in-the-str

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!