1 var baseToString = require('../internal/baseToString'),
2 escapeHtmlChar = require('../internal/escapeHtmlChar');
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 characters
13 * 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 Internet Explorer < 9, they can break out
22 * of 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 // Reset `lastIndex` because in IE < 9 `String#replace` does not.
42 string = baseToString(string);
43 return (string && reHasUnescapedHtml.test(string))
44 ? string.replace(reUnescapedHtml, escapeHtmlChar)
48 module.exports = escape;