[英]Escaping html characters in a javascript array
I would like to escape some html characters that I have stored in an array. 我想转义一些我存储在数组中的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"
}];
I know that there are multiple answers to escaping html tags within javascript. 我知道在javascript中转义html标签有多个答案。 For example I found this function which is very straightforward.
例如,我发现此功能非常简单。
var htmlString = "<h1>My HTML STRING</h1><p>It has html characters & such in it.</p>";
$(document).ready(function(){
$("#replaceDiv").text(htmlString)
});
However, all the solutions I have seen require creating a function assigning variables etc. This seems overly complicated. 但是,我看到的所有解决方案都需要创建一个分配变量等的函数。这似乎过于复杂。 Is there any easier way to accomplish my goals here?
在这里有没有更简单的方法可以实现我的目标?
Thanks @GrawCube for help in the chat room. 感谢@GrawCube在聊天室提供的帮助。
Solution was to create an escape function
and then parse the quiz
array. 解决方案是创建一个
escape function
,然后解析quiz
数组。
function escapeHtmlChars(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
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]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.