转义javascript数组中的html字符

时间:2015-03-30 15:54:33

标签: javascript html escaping

我想要转义一些存储在数组中的html字符。

var quiz = [{
    "question": "How would we use css to select an element with <h1 class = \"intro\">",
    "choices": [".intro{ property: attribute }", "intro{ property :attribute }", "#intro{property: attribute }"],
    "correct": ".intro{ property: attribute }"
}, {
    "question": "How would we select the element with id firstname <p id=\"firstname\">?",
    "choices": ["#firstname{ property: attribute }", ".firstname{ property: attribute }", "who cares?"],
    "correct": "#firstname{ property: attribute }"
}, {
    "question": "How would we select all elements?",
    "choices": ["#{ property: attribute }",  "@all{ property: attribute }", "*{ property: attribute }"],
    "correct": "*{ property: attribute }"
}, {
    "question": "what does this do div > p?",
    "choices": ["Selects all <p> elements inside <div> elements", "Selects <p> element that is a child of <div>", "Selects all <p> that are placed immediately after <div>"],
    "correct": "Selects <p> element that is a child of <div>"
}, {
    "question": "what does div + p do?",
    "choices": ["Selects all <div> and <p> elements", "Selects all <p> elements inside <div> elements", "Selects all <p> elements that are placed immediately after <div> elements"],
    "correct": "Selects all <p> elements that are placed immediately after <div> elements"
}];

我知道在javascript中转义html标签有多个答案。例如,我发现这个功能非常简单。

var htmlString = "<h1>My HTML STRING</h1><p>It has html characters & such in it.</p>";
  $(document).ready(function(){
      $("#replaceDiv").text(htmlString)
   });

然而,我所看到的所有解决方案都需要创建一个赋值变量等函数。这看起来过于复杂。有没有更简单的方法来实现我的目标?

1 个答案:

答案 0 :(得分:0)

感谢@GrawCube在聊天室中提供帮助。

解决方案是创建escape function,然后解析quiz数组。

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

for (var i = 0; i < quiz.length; i++) {
    quiz[i].correct = escapeHtmlChars(quiz[i].correct);
    for (var j = 0; j < quiz[i].choices.length; j++) {
        quiz[i].choices[j] = escapeHtmlChars(quiz[i].choices[j]);
    }
}