Please explain me that function

Hey, could anyone explain me step by step below function:

function convertHTML(str) {
  const htmlEntities = {
    '&': '&',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&apos;'
  return str.replace(/([&<>"'])/g, (i) => htmlEntities[i]);

convertHTML("Dolce & Gabbana");

Especially part with (i) => htmlEntities[i]); I am not sure how it work. How function know which index use.

Thanks in advance :slight_smile:

this is an arrow function, a ES6 feature that make functions more compact, with some variations in properties

the replace method can take a callback, and it will give to the callback each match of the regex, and will change it with the return value from the callback function

you can read more about replace in the documentation

1 Like

htmlEntities is an object with key value pairs.
using the String method .replace() you are passing in the keys &<>"' and then replacing them with a callback function which returns their value.

How function know which index use?

All the function does is return the value of whatever key is passed in. So if you pass in ‘&’ it is going to return ‘&amp;’ it will then replace the ‘&’ in the string with the returned value (&amp;). The ‘g’ flag on the regex means that it will replace all instances rather than just the first.

I hope that makes sense. Happy coding :slight_smile:

1 Like

Let’s go step by step:

1- convertHTML(str) accepts strings as parameters.

2- htmlEntities contains the characters to be replaced. Why should you replace? Because if you want to use in a paragraph "<" or ">" this will give you unwanted effects.

3- return str.replace() returns the string with the characters replaced.

replace(regex, callback)

regex: Search the specified characters in the string (& < >" ')

/([&<>"'])/g the g at the end is for you to search the entire string, without the g it would only search until you find a single match.

callback: See it this way, with each match in ‘regex’ it passes the callback as parameter, then callback does something with it. Using object notation, find the property value using the character.

An example:

 let changeFor = {
 'e': 'x'
 let str = 'Hello, im Gabriel'
 str.replace (/e/g, (characterMatch)=>changeFor[characterMatch])

The callback returns a character with which it will be changed in the string

With each coincidence of the letter ‘e’, ​​the callback will return the letter ‘x’
changeFor['e'] // 'x'
and it will be used to change the ‘e’.

this would result in:

// Hxllo, im Gabrixl

–The syntax used is called Arrow Functions

(i) => htmlEntities [i]

is the same as

function (i) {
return htmlEntities [i]

sorry for the bad English

1 Like

Thank you for very detailed explanation. I wasn’t sure with callback part, now it’s clear for me :slight_smile: