2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
8 YUI.add('escape', function(Y) {
11 * Provides utility methods for escaping strings.
30 // -- Public Static Methods ------------------------------------------------
34 * Returns a copy of the specified string with special HTML characters
35 * escaped. The following characters will be converted to their
36 * corresponding character entities:
37 * <code>& < > " ' / `</code>
41 * This implementation is based on the
42 * <a href="http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet">OWASP
43 * HTML escaping recommendations</a>. In addition to the characters
44 * in the OWASP recommendation, we also escape the <code>`</code>
45 * character, since IE interprets it as an attribute delimiter when used in
50 * @param {String} string String to escape.
51 * @return {String} Escaped string.
54 html: function (string) {
55 return string.replace(/[&<>"'\/`]/g, Escape._htmlReplacer);
59 * Returns a copy of the specified string with special regular expression
60 * characters escaped, allowing the string to be used safely inside a regex.
61 * The following characters, and all whitespace characters, are escaped:
62 * <code>- # $ ^ * ( ) + [ ] { } | \ , . ?</code>
65 * @param {String} string String to escape.
66 * @return {String} Escaped string.
69 regex: function (string) {
70 return string.replace(/[\-#$\^*()+\[\]{}|\\,.?\s]/g, '\\$&');
73 // -- Protected Static Methods ---------------------------------------------
76 * Regex replacer for HTML escaping.
78 * @method _htmlReplacer
79 * @param {String} match Matched character (must exist in HTML_CHARS).
80 * @returns {String} HTML entity.
84 _htmlReplacer: function (match) {
85 return HTML_CHARS[match];
89 Escape.regexp = Escape.regex;