https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-convert-html-entities/16007


转实体

  1. const htmlEntities = {
  2. "&": "&",
  3. "<": "&lt;",
  4. ">": "&gt;",
  5. '"': "&quot;",
  6. "'": "&apos;"
  7. };


使用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

  1. function convertHTML(str) {
  2. const htmlEntities = {
  3. "&": "&amp;",
  4. "<": "&lt;",
  5. ">": "&gt;",
  6. '"': "&quot;",
  7. "'": "&apos;"
  8. };
  9. return str.split("").map(x=>htmlEntities[x]||x).join('');
  10. }
  11. console.log(
  12. convertHTML("Dolce & Gabbana")
  13. )

join()默认用的是逗号,连接的

要想使用空字符串连接,需要使用’’

使用replace,replace第二个参数可以是函数

  1. function convertHTML(str) {
  2. // Use Object Lookup to declare as many HTML entities as needed.
  3. const htmlEntities = {
  4. "&": "&amp;",
  5. "<": "&lt;",
  6. ">": "&gt;",
  7. '"': "&quot;",
  8. "'": "&apos;"
  9. };
  10. // Using a regex, replace characters with it's corresponding html entity
  11. return str.replace(/([&<>\"'])/g, match => htmlEntities[match]);
  12. }
  13. // test here
  14. convertHTML("Dolce & Gabbana");

使用switch

  1. function convertHTML(str) {
  2. // Split by character to avoid problems.
  3. var temp = str.split("");
  4. // Since we are only checking for a few HTML elements, use a switch
  5. for (var i = 0; i < temp.length; i++) {
  6. switch (temp[i]) {
  7. case "<":
  8. temp[i] = "&lt;";
  9. break;
  10. case "&":
  11. temp[i] = "&amp;";
  12. break;
  13. case ">":
  14. temp[i] = "&gt;";
  15. break;
  16. case '"':
  17. temp[i] = "&quot;";
  18. break;
  19. case "'":
  20. temp[i] = "&apos;";
  21. break;
  22. }
  23. }
  24. temp = temp.join("");
  25. return temp;
  26. }
  27. //test here
  28. convertHTML("Dolce & Gabbana");