I’ve got this statement to solve in Javascript:
Convert the characters &, <, >, " (double quote), and ‘ (apostrophe), in a string to their corresponding HTML entities.
This is my solution but it doesn’t change < into the HTML corresponding entity. This is the result of console.log(newStr);:
<>
As you can see, it changes the second symbol but not the first one and I need to know why. This is my code:
function convertHTML(str) {
let newStr;
let i = 0;
while ( i < str.length){
console.log(str[i]);
if(str[i] === '&'){
newStr = str.replace( /&/g , '&');
}else if (str[i] === '<'){
newStr = str.replace( /</g , '<');
}else if (str[i] === '>'){
newStr = str.replace( />/g , '>');
}else if(str[i] === '"'){
newStr = str.replace( /"/g , '"');
}else if (str[i] === "'"){
newStr = str.replace( /'/g , ''');
}
i++
}
console.log(newStr);
return newStr
}
convertHTML("<>");
I know there are much much better solutions, but I’m new and if I don’t know where’s the mistake I can’t understand. Thanks in advance.
>Solution :
This happens because with each replace call, you start again from the original string, not from the one you got in the previous iteration of the loop. As a consequence, only the last call to replace is reflected in newStr.
I would suggest to not loop at all, because those replace calls will scan the whole string anyway, and will replace all the occurrences of the character that is searched.
So, just call all five types of replace in one chain:
let newStr = str.replace( /&/g , '&')
.replace( /</g , '<')
.replace( />/g , '>')
.replace( /"/g , '"')
.replace( /'/g , ''');