Javascript and Regex Doubt

Question:

Convert the characters & , < , > , " (double quote), and ' (apostrophe), in a string to their corresponding HTML entities.

Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.

Answer:

function convertHTML(str) {
  let dic = {
    '&':'&amp;',
    '<':'&lt;',
    '>':'&gt;',
    '"':'&quot;',
    "'":"&apos;"
  }
  str = str.replace(str.match(/[&<>"']/g),dic[str.match(/[&<>"']/)])
  return str;
}

convertHTML("Dolce & Gabbana");

Can someone tell me why it’s wrong?

Thanks in advance!

You are so close!

Your problem is not with your regular expressions but with parameters to str.replace() method.

 str = str.replace(str.match(/[&<>"']/g),dic[str.match(/[&<>"']/)])

First parameter to str.replace should be either a regex or string. The result of str.match is an array.

1 Like

What would be the correct way?

str = str.replace(str.match(/[&<>"’]/g)[0],dic[str.match(/[&<>"’]/)[0]]) ?

Just use your first regex as the first parameter - no need for the str.match. All the matches to that will be sent to your replacer (second parameter).

1 Like

str = str.replace(/[&<>"’]/g,dic[str.match(/[&<>"’]/g)[0]])

It worked, but I cant do that:

convertHTML("<>")should return&​lt;&​gt;` .

convertHTML(β€œabc”)should returnabc` .

Any thoughts on that?

Doh! Overlooked something. The second parameter would always return the first match wouldn’t it?

string.replace can take function as second parameter. That function is called on every match and is passed the matching substring as its first parameter.

str = str.replace( /[&<>"']/g,lookup(match) )

So a short function that looked up the entity in dic would work. Like lookup(’<’) returns β€œ&lt”, lookup(’&’) returns β€˜β€™&amp". It could even be an arrow function.

1 Like