escape.js 1.8 KB

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