正在转义javascript数组中的html字符

Escaping html characters in a javascript array

本文关键字:html 字符 数组 转义 javascript      更新时间:2023-09-26

我想转义存储在数组中的一些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)
   });

然而,我看到的所有解决方案都需要创建一个分配变量等的函数。这似乎过于复杂。有什么更容易的方法来实现我的目标吗?

感谢@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]);
    }
}