Escape HTML entities
The moment you build markup from a string, unescaped user input becomes an injection bug. Server-side renderers and template engines escape by default; when you build HTML by hand you have to do it yourself.
Implement escapeHtml(input). Replace, in this order, & with &, < with <, > with >, " with " and ' with '. Every occurrence is replaced, not just the first.
The ampersand must be replaced first, so text that already contains an entity is escaped again: "<" becomes "&lt;". If input is null or undefined, return the empty string ""; any other non-string value is converted with String(input) before escaping.
Arguments
inputstring | null | undefined- The text to escape.
nullandundefinedare treated as the empty string; other non-strings are converted withString(input)first.
Returns
string — A copy of the input with & < > " ' replaced by their HTML entity equivalents.
Examples
escapeHtml('<a href="x">Hi & bye</a>');
// => "<a href="x">Hi & bye</a>"Angle brackets, quotes and ampersands are all replaced.
escapeHtml("<");
// => "&lt;"The ampersand is escaped first, so an already-escaped entity is double-escaped.
escapeHtml(null);
// => ""null and undefined both collapse to the empty string.
What it has to do
- Replace all five characters
& < > " 'with& < > " 'respectively. - Replace every occurrence, not just the first.
- Escape ampersands first, so
<becomes&lt;. - Return
""fornullandundefinedinput. - Leave text with none of those characters untouched.
Notes
- This is a one-way transform meant for text content inside HTML. For attribute values you should also escape
'(which this does), and forhref/srcyou need a URL-aware escape on top. 'is the numeric form of the apostrophe entity because the named'is not part of HTML 4; the numeric form works everywhere.
Stuck? The javascript course covers everything this challenge needs.
- 1.escapes angle brackets, quotes and ampersands
- 2.escapes single quotes as '
- 3.escapes the ampersand first so entities are double escaped
- 4.leaves plain text untouched
- 5.returns an empty string for null
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.