escape.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. var escapeHtmlChar = require('./_escapeHtmlChar'),
  2. toString = require('./toString');
  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
  11. * characters 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. See
  16. * [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 IE < 9, they can break out of
  20. * 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
  23. * [HTML5 Security Cheatsheet](https://html5sec.org/) for more details.
  24. *
  25. * When working with HTML you should always
  26. * [quote attribute values](http://wonko.com/post/html-escaping) to reduce
  27. * XSS vectors.
  28. *
  29. * @static
  30. * @since 0.1.0
  31. * @memberOf _
  32. * @category String
  33. * @param {string} [string=''] The string to escape.
  34. * @returns {string} Returns the escaped string.
  35. * @example
  36. *
  37. * _.escape('fred, barney, & pebbles');
  38. * // => 'fred, barney, &amp; pebbles'
  39. */
  40. function escape(string) {
  41. string = toString(string);
  42. return (string && reHasUnescapedHtml.test(string))
  43. ? string.replace(reUnescapedHtml, escapeHtmlChar)
  44. : string;
  45. }
  46. module.exports = escape;