My Codewars sollution is almost identical to the real one but does not work. Does someone know why?

36 views Asked by At

I was doing a Codewars challenge called Safen User Input Part I - htmlspecialchars. The objective is to replace special characters with html entities. I came up with the solution on top and it did not work but the code on the bottom was successful. As you can see the only difference is the order they are listed. Why doesn't my code work?

function htmlspecialchars(formData) {
    return formData.replaceAll('<', "&lt;")
                 .replaceAll('>', "&gt;")
                 .replaceAll('"', "&quot;")
                 .replaceAll('&', "&amp;");
}

function htmlspecialchars(formData) {
    return formData.replaceAll('&', "&amp;")
                 .replaceAll('"', "&quot;")
                 .replaceAll('<', "&lt;")
                 .replaceAll('>', "&gt;");
}
1

There are 1 answers

0
Natrium On

In your solution, < will become &lt; in the first place (.replaceAll('<', "&lt;")), but then in the final step (.replaceAll('&', "&amp;")) it becomes &amp;lt; which is not correct.

The correct order of execution is important.

It's just a matter of debugging to find the problem.