Why similar escaping codes do not work for html escaping in html elements if ampersand is not escaped first? After I put & to the first place everything works.
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
Thanks
Why similar escaping codes do not work for html escaping in html elements if ampersand is not escaped first? After I put & to the first place everything works.
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
Thanks
Share Improve this question asked Aug 8, 2014 at 18:38 user3695711user3695711 751 silver badge8 bronze badges 4- Think about it. If you're first replacing some characters with an ampersand and then afterwards replace ampersands... uhm... – deceze ♦ Commented Aug 8, 2014 at 18:40
-
Look at the other 4 items. What do they start with? What will happen if you replace
&
last? – Wooble Commented Aug 8, 2014 at 18:40 - Yes, I suspected this... But why downvotes? Too trivial a question is? – user3695711 Commented Aug 8, 2014 at 18:49
- unfortunately yes @user3695711 I wouldn't personally downvote because what one feel is trivial, others feel a little research might have found the answer. – GeekByDesign Commented Aug 8, 2014 at 19:20
1 Answer
Reset to default 7Consider what happens:
This sentence has an <html> tag in it
If you do the <>
replacements first, you end up with
This sentence has an <html> tag in it
Then you do the &
replacement, and get
This sentence has an &lt;html&gt; tag in it
Now your <
and >
are corrupted because the <>
characters have been double-encoded.
If you encode &
first, things "Just work".