https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-convert-html-entities/16007
转实体
const htmlEntities = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'"
};
使用encodeURIComponent(‘ % ‘)
转成了%20%26%20
Convert HTML Entities
Convert the characters &
, <
, >
, "
(double quote), and '
(apostrophe), in a string to their corresponding HTML entities.
使用split,map,join
function convertHTML(str) {
const htmlEntities = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'"
};
return str.split("").map(x=>htmlEntities[x]||x).join('');
}
console.log(
convertHTML("Dolce & Gabbana")
)
join()默认用的是逗号,连接的
要想使用空字符串连接,需要使用’’
使用replace,replace第二个参数可以是函数
function convertHTML(str) {
// Use Object Lookup to declare as many HTML entities as needed.
const htmlEntities = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'"
};
// Using a regex, replace characters with it's corresponding html entity
return str.replace(/([&<>\"'])/g, match => htmlEntities[match]);
}
// test here
convertHTML("Dolce & Gabbana");
使用switch
function convertHTML(str) {
// Split by character to avoid problems.
var temp = str.split("");
// Since we are only checking for a few HTML elements, use a switch
for (var i = 0; i < temp.length; i++) {
switch (temp[i]) {
case "<":
temp[i] = "<";
break;
case "&":
temp[i] = "&";
break;
case ">":
temp[i] = ">";
break;
case '"':
temp[i] = """;
break;
case "'":
temp[i] = "'";
break;
}
}
temp = temp.join("");
return temp;
}
//test here
convertHTML("Dolce & Gabbana");