escape.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 their
  8. * 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. * When working with HTML you should always
  20. * [quote attribute values](http://wonko.com/post/html-escaping) to reduce
  21. * XSS vectors.
  22. *
  23. * @static
  24. * @since 0.1.0
  25. * @memberOf _
  26. * @category String
  27. * @param {string} [string=''] The string to escape.
  28. * @returns {string} Returns the escaped string.
  29. * @example
  30. *
  31. * _.escape('fred, barney, & pebbles');
  32. * // => 'fred, barney, &amp; pebbles'
  33. */
  34. function escape(string) {
  35. string = toString(string);
  36. return (string && reHasUnescapedHtml.test(string))
  37. ? string.replace(reUnescapedHtml, escapeHtmlChar)
  38. : string;
  39. }
  40. module.exports = escape;