[Convert HTML Entities] I don't understand the advanced code solution here

Hello Campers,

I just passed through the ‘Convert HTML Entities’, but i was curious to lookup the other possible solutions on FCC’s github. And as I know how .map() works, I don’t get a part of this snippet:

function convertHTML(str) {
  // Use Object Lookup to declare as many HTML entities as needed.
  //Use map function to return a filtered str with all entities changed automatically.
  return str.split('').map(function(entity){
    return htmlEntities[entity] || entity;  //  WHAAAAT ???

// test here
convertHTML("Dolce & Gabbana");

How does the return statement in return htmlEntities[entity] || entity; know to choose the first one when there’s a match? I mean after all this is an ALTERNATIVE, right? so how?

Thanks for any trial of making this clear to me :slight_smile:

1 Like

I’m glad it didn’t look strange for me only :slight_smile: thank you

Goodness - and to think I spent the last hour on this getting

function convertHTML(str) {
  // &colon;&rpar;
  var replacement = {"&": "&amp;", ">": "&gt;", "<": "&lt;", "'": "&apos;", "\"": "&quot;"};
  var regex = /[&><'"]/g;
  if (str.match(regex) !== null) {
    var testArray = str.match(regex);
    for (i=0; i<testArray.length;i++) {
      x = testArray[i];
      str = str.replace(x, replacement[x]);
    return str;
  } else {
    return str;

the replace description on MDN wasn’t entirely clear - I like the second answer given


I generally don’t look at others solutions for the algorithms but for this one I did as I thought that what I had created was frankly appalling, even though it worked.

Hey it works!!!

function convertHTML(str) {
  var result = "";
  result = str.replace(/[&<>"']/g, function (value){
    switch (value){
        case "&":
          return "&amp;";
        case "<":
          return "&lt;";
        case ">":
          return "&gt;";
        case '"':
          return "&quot;";
        case "'":
          return "&apos;";
  return result;

convertHTML("Dolce & Gabbana");

Apart from the fact that I used a switch statement as opposed to creating an object to store the values, I am feeling rather happier after seeing @P1xt’s example.

@p1xt My understanding is that using the || operator in this way is the primary (and accepted) way of giving function arguments default values:

function foo (bar) {
  bar=bar || 8;

or checking for browser support:

audioContext = window.AudioContext || window.webkitAudioContext;

So why would it be an issue to use it in the way demonstrated in the first post?

me too ,I didn’t understand this advanced solution,because they use || (or operator) ,so what I think is maybe the map function will take the other choice wich is entity.