Converting html entities

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 :slight_smile:

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.

Challenge: Convert HTML Entities

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/convert-html-entities

Take a look at line:
let matchedStrs= str.match(regExSymbols);
What happens if str doesn’t have any of the characters that needs converting?

Thank you, good point, unfortunately it doesn’t solve my problem :slight_smile:

Sorry, but I have added a test for null, and the str still returns the html characters,

&lt;    returns < 

I’m really confused about what you could mean then ?

Here it is :slight_smile:

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 :slight_smile:

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;
}

I just used a document.write statement to output the tests on my laptop ide?
but it shows the html entities as html characters:

document.write(convertHTML(“Schindler’s List”)); //my laptop output: Shindler’s List

Thanks :slight_smile:

Thanks . I have to remember this for future projects, I wasted a few days on this one when it was correct all along :slight_smile: