Tell us what’s happening:
Hi,
My regex is matching just the first match. However, in my debugger regex
value is /&/g
(when "Dolce & Gabbana"
). So, I was hoping as much matches as existing in (in "Dolce & & Gabbana"
should be 2 to be replaced). I also tried with a function as 2nd parameter (bottom): same results. What am I missing guys?
Your code so far
function convertHTML(str) {
const reservedChars = ["&","<",">", "","'"];
const dictionaryOfEntities = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
}
let reserved = str.split('').filter(char => reservedChars.indexOf(char) !== -1)
let regex = new RegExp (`${reserved}`,'g')
if (reserved.length === 0) return str
else return str.replace(regex, dictionaryOfEntities[reserved])
}
console.log(convertHTML("Dolce & Gabbana"));//-> "Dolce & Gabbana"
console.log(convertHTML("Dolce & & Gabbana"));//-> "Dolce & & Gabbana"
function convertHTML(str) {
const reservedChars = ["&","<",">", "","'"];
const dictionaryOfEntities = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
}
let reserved = str.split('').filter(char => reservedChars.indexOf(char) !== -1)
let regex = new RegExp (`${reserved}`,'g')
if (reserved.length === 0) return str
else return str.replace(regex, entity)
function entity (match){
return match.replace(match, dictionaryOfEntities[reserved])
}
}
console.log(convertHTML("Dolce & Gabbana"));//-> "Dolce & Gabbana"
console.log(convertHTML("Dolce & & Gabbana"));//-> "Dolce & & Gabbana"
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36 OPR/67.0.3575.115
.
Challenge: Convert HTML Entities
Link to the challenge: