Hi all,
I’m wondering why my code won’t work.
It keeps converting the ‘&’ + str to the ascii characters anyway.
I tried escaping the & , tried JSON stringify , nothing seems to do it.
Hope someone can help . Thanks
Your code so far
function convertHTML(str) {
let regExSymbols = /[&<>"']/g;
let lookup = { 34:"quot;",38:"amp;",39:"apos;",60:"lt;",62:"gt;"};
let matchedStrs= str.match(regExSymbols);
for(let i=0;i<matchedStrs.length;++i){
let index = str.search(matchedStrs[i]);
let charcode = str.charCodeAt(index);
let newStr = lookup[charcode];
str = str.replace(str.charAt(index),'&'+ newStr);
}
return str;
}
convertHTML("Dolce & Gabbana");
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0.
The line referenced by @sanity is important to solving your problem. What should happen if the match method returns null? It will return null if there was no match of the characters. Do you understand what error is caused when the for loop tries to evaluate the i < matchedStrs.length condition if matchedStrs is null? If you do not, then check the browser’s console to find out.
let regExSymbols = /[&<>"']/g;
let lookup = { 34:"quot;",38:"amp;",39:"apos;",60:"lt;",62:"gt;"};
let matchedStrs= str.match(regExSymbols);
if (!(matchedStrs===null)){
for(let i=0;i<matchedStrs.length;++i){
let index = str.search(matchedStrs[i]);
let charcode = str.charCodeAt(index);
let newStr = lookup[charcode];
str = str.replace(str.charAt(index),'&'+ newStr);
}
}
return str;
Oke my full code. I actually had the simpler (matchedStrs) first but then doubted it to be correct. It still doesn’t make a difference though:
Thank you btw
function convertHTML(str) {
let regExSymbols = /[&<>"']/g;
let lookup = { 34:"quot;",38:"amp;",39:"apos;",60:"lt;",62:"gt;"};
let matchedStrs= str.match(regExSymbols);
if (matchedStrs){
for(let i=0;i<matchedStrs.length;++i){
let index = str.search(matchedStrs[i]);
let charcode = str.charCodeAt(index);
let newStr = lookup[charcode];
str = str.replace(str.charAt(index),'&'+ newStr);
}
}
return str;
}
The latest code you posted passes all the tests for me. What tests are you failing? Do you see any errors showing in the browser console when you click Run Tests?
If you use document.write, then the ' would still display as the string you originally passed to it. If you write console.log(convertHTML("Schindler's List")); and then look at your console when executing the code, you will see the conversion.