3 ms·
It's hard to belive that JavaScript still does not have standard function to encodeHTML to string (as in replace < and > etc with < etc). I know this can be sol
by czechdeveloper 5y ago
It's hard to belive that JavaScript still does not have standard function to encodeHTML to string (as in replace < and > etc with < etc). I know this can be solved by other wasy (as in never using innerHTML), but in reality it's often ignored or just custom implementations put in place.
- mark_and_sweep 5y agoI think part of the reason that we don't have such a function yet is that it is essentially a one-liner if you use decimal notation for entities: function escape_html(s) { return s.replace(/[&<>"']/g, m => `&#${m.charCodeAt(0)};`) } That being said, a built-in function would be convenient and faster.
- herodoturtle 5y agoThere are many built-in functions that could also be accomplished with a one-liner akin to your example. I hear what you're saying - there's an easy manual workaround for this requirement - but a built-in function would still add value nonetheless.
- mark_and_sweep 5y agoAgreed. As I said, it would be convenient, faster, and most importantly, guaranteed to be error-free.
- felixfbecker 5y agoThe `textContent` setter also does this. E.g. you can do this: const span = document.createElement('span') span.textContent = text return span.innerHTML
- czechdeveloper 5y agoThis does not handle quotes as far as I remember
- ufo 5y agoOne problem is that it's just as simple to implement an incirrect version of this function
- SCLeo 5y agoSorry for my ignorance, but why do you need to replace "<" and ">" etc with "<" etc? If I am not wrong: - When the user input is plaintext, you will output using .innerText, which means such replacement will actually break those special characters. - When the user input is actual html (or contenteditable), such replacement will also break those tags. If you don't want tags in the first place, why make so that user inputs html?