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 = {
'&':'&',
'<':'<',
'>':'>',
'"':'"',
"'":"'"
}
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 β<β, lookup(β&β) returns ββ&". It could even be an arrow function.
1 Like