3 Copyright 2012 Yahoo! Inc. All rights reserved.
4 Licensed under the BSD License.
5 http://yuilibrary.com/license/
7 YUI.add('escape', function(Y) {
10 Provides utility methods for escaping strings.
29 // -- Public Static Methods ------------------------------------------------
32 Returns a copy of the specified string with special HTML characters
33 escaped. The following characters will be converted to their
34 corresponding character entities:
38 This implementation is based on the [OWASP HTML escaping
39 recommendations][1]. In addition to the characters in the OWASP
40 recommendations, we also escape the <code>`</code> character, since IE
41 interprets it as an attribute delimiter.
43 If _string_ is not already a string, it will be coerced to a string.
45 [1]: http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
48 @param {String} string String to escape.
49 @return {String} Escaped string.
52 html: function (string) {
53 return (string + '').replace(/[&<>"'\/`]/g, Escape._htmlReplacer);
57 Returns a copy of the specified string with special regular expression
58 characters escaped, allowing the string to be used safely inside a regex.
59 The following characters, and all whitespace characters, are escaped:
61 - $ ^ * ( ) + [ ] { } | \ , . ?
63 If _string_ is not already a string, it will be coerced to a string.
66 @param {String} string String to escape.
67 @return {String} Escaped string.
70 regex: function (string) {
71 // There's no need to escape !, =, and : since they only have meaning
72 // when they follow a parenthesized ?, as in (?:...), and we already
73 // escape parens and question marks.
74 return (string + '').replace(/[\-$\^*()+\[\]{}|\\,.?\s]/g, '\\$&');
77 // -- Protected Static Methods ---------------------------------------------
80 * Regex replacer for HTML escaping.
82 * @method _htmlReplacer
83 * @param {String} match Matched character (must exist in HTML_CHARS).
84 * @returns {String} HTML entity.
88 _htmlReplacer: function (match) {
89 return HTML_CHARS[match];
93 Escape.regexp = Escape.regex;
98 }, '3.5.0' ,{requires:['yui-base']});