1 var escapeHtmlChar = require('./_escapeHtmlChar'),
2 toString = require('./toString');
4 /** Used to match HTML entities and HTML characters. */
5 var reUnescapedHtml = /[&<>"'`]/g,
6 reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
9 * Converts the characters "&", "<", ">", '"', "'", and "\`" in `string` to
10 * their corresponding HTML entities.
12 * **Note:** No other characters are escaped. To escape additional
13 * characters use a third-party library like [_he_](https://mths.be/he).
15 * Though the ">" character is escaped for symmetry, characters like
16 * ">" and "/" don't need escaping in HTML and have no special meaning
17 * unless they're part of a tag or unquoted attribute value.
18 * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
19 * (under "semi-related fun fact") for more details.
21 * Backticks are escaped because in IE < 9, they can break out of
22 * attribute values or HTML comments. See [#59](https://html5sec.org/#59),
23 * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and
24 * [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/)
27 * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping)
28 * to reduce XSS vectors.
33 * @param {string} [string=''] The string to escape.
34 * @returns {string} Returns the escaped string.
37 * _.escape('fred, barney, & pebbles');
38 * // => 'fred, barney, & pebbles'
40 function escape(string) {
41 string = toString(string);
42 return (string && reHasUnescapedHtml.test(string))
43 ? string.replace(reUnescapedHtml, escapeHtmlChar)
47 module.exports = escape;