0
function convertHTML(str) {
let html = {
  "&": "&",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&apos;"
}

let regex = /[<>"'&])/gi;
// let strMatch = str.match(regex);

// Using a regex, replace characters with it's corresponding html entity
  return str.replace(/[&<>\"'])/g, match => html[match]);
}

convertHTML("<>");

I've never come across this before, but on the return statement, it just says "match" without a dot - how does JS know what it's trying to apply the match function on?

Also, what does the arrow symbol do in this case?

Ps i'm very newbie, if you could explain it as simple as possible. Thank you :)

I tried to use a predefined variable which matched all the possible 'html' entities. e.g let strMatch = str.match(regex).

Using this variable, i then applied it to the replace function. str.replace(strMatch, match[strMatch])

This obviously presented problems as there could be more than one object in the match array.

I managed to figure this using an alternative method, but once completed I also looked at the solution above and it didn't quite add up.

  • 2
    `match` isn't the name of the function. This is an arrow function, `match` is the argument. It's equivalent to `function(match) { return html[match]; }` – Barmar Nov 08 '22 at 22:21
  • See the docs about how [specifying a function as the replacement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_function_as_the_replacement) works. – Wyck Nov 08 '22 at 22:22

0 Answers0