by czechdeveloper · 5y ago · 0 comments
function escape_html(s) { return s.replace(/[&<>"']/g, m => `&#${m.charCodeAt(0)};`) }
That being said, a built-in function would be convenient and faster.
const span = document.createElement('span')
span.textContent = text
return span.innerHTMLI hear what you're saying - there's an easy manual workaround for this requirement - but a built-in function would still add value nonetheless.
- 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?