Convert HTML Entities regEx problem

Tell us what’s happening:

Your code so far

function convertHTML(str) {
  for(let i = 0; i < str.length; i++){
    if(str.charAt(i) == /[&<>"']/gi)
      // Do something if my condition evaluates to true
  }
  return str;
}

convertHTML("Dolce & Gabbana");

I tried to do something like this but it seems like it won´t accept my regEx as valid input since my if statement never evaluates to true. Do i have the regEx wrong or is it not possible to solve this using regEx like that?

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0.

It is possible to solve it using regex, but not like that: you are comparing a string to a regex, you are not using the regex to check the string (you would need to use one of the methods the use regular expressions for that, test(), match()…)

Remember that you need a different action for each symbol

1 Like

Thank you very much for the answer!
So what you´re saying is that simple if/else if statements are the way to go?
I was hoping for a simpler and more elegant solution than that!

I don’t know what you would consider elegant, but there are many ways to solve this, if/else statements are a possible way

Find one that works, then you can spend all the time you want in solving it elegantly

Usually the most elegant bits of code (most importantly, readable) are far from simple to come up with, even if they may seem so at first glance - but usually they comes from a lot of tries and experience.

Have you considered using the replace command instead of attempting to resolve this using regex?

Not really, as I´m not quite comfortabelt witht he replace method yet, but I´ll give it a try and learn something new!

Here is a resource that you may find useful: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Thank you for the resource!
I used a mixture of if statements and replace to get the code to work.