Version 3.18.1
Show:

File: escape/js/escape.js

  1. /**
  2. Provides utility methods for escaping strings.
  3. @module escape
  4. @class Escape
  5. @static
  6. @since 3.3.0
  7. **/
  8. var HTML_CHARS = {
  9. '&': '&',
  10. '<': '&lt;',
  11. '>': '&gt;',
  12. '"': '&quot;',
  13. "'": '&#x27;',
  14. '/': '&#x2F;',
  15. '`': '&#x60;'
  16. },
  17. Escape = {
  18. // -- Public Static Methods ------------------------------------------------
  19. /**
  20. Returns a copy of the specified string with special HTML characters
  21. escaped. The following characters will be converted to their
  22. corresponding character entities:
  23. & < > " ' / `
  24. This implementation is based on the [OWASP HTML escaping
  25. recommendations][1]. In addition to the characters in the OWASP
  26. recommendations, we also escape the <code>&#x60;</code> character, since IE
  27. interprets it as an attribute delimiter.
  28. If _string_ is not already a string, it will be coerced to a string.
  29. [1]: http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
  30. @method html
  31. @param {String} string String to escape.
  32. @return {String} Escaped string.
  33. @static
  34. **/
  35. html: function (string) {
  36. return (string + '').replace(/[&<>"'\/`]/g, Escape._htmlReplacer);
  37. },
  38. /**
  39. Returns a copy of the specified string with special regular expression
  40. characters escaped, allowing the string to be used safely inside a regex.
  41. The following characters, and all whitespace characters, are escaped:
  42. - $ ^ * ( ) + [ ] { } | \ , . ?
  43. If _string_ is not already a string, it will be coerced to a string.
  44. @method regex
  45. @param {String} string String to escape.
  46. @return {String} Escaped string.
  47. @static
  48. **/
  49. regex: function (string) {
  50. // There's no need to escape !, =, and : since they only have meaning
  51. // when they follow a parenthesized ?, as in (?:...), and we already
  52. // escape parens and question marks.
  53. return (string + '').replace(/[\-$\^*()+\[\]{}|\\,.?\s]/g, '\\$&');
  54. },
  55. // -- Protected Static Methods ---------------------------------------------
  56. /**
  57. * Regex replacer for HTML escaping.
  58. *
  59. * @method _htmlReplacer
  60. * @param {String} match Matched character (must exist in HTML_CHARS).
  61. * @return {String} HTML entity.
  62. * @static
  63. * @protected
  64. */
  65. _htmlReplacer: function (match) {
  66. return HTML_CHARS[match];
  67. }
  68. };
  69. Escape.regexp = Escape.regex;
  70. Y.Escape = Escape;