Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80677 views
1
/**
2
* lodash 3.0.0 (Custom Build) <https://lodash.com/>
3
* Build: `lodash modern modularize exports="npm" -o ./`
4
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
5
* Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
6
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
7
* Available under MIT license <https://lodash.com/license>
8
*/
9
var baseToString = require('lodash._basetostring');
10
11
/** Used to match HTML entities and HTML characters. */
12
var reUnescapedHtml = /[&<>"'`]/g,
13
reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
14
15
/** Used to map characters to HTML entities. */
16
var htmlEscapes = {
17
'&': '&amp;',
18
'<': '&lt;',
19
'>': '&gt;',
20
'"': '&quot;',
21
"'": '&#39;',
22
'`': '&#96;'
23
};
24
25
/**
26
* Used by `_.escape` to convert characters to HTML entities.
27
*
28
* @private
29
* @param {string} chr The matched character to escape.
30
* @returns {string} Returns the escaped character.
31
*/
32
function escapeHtmlChar(chr) {
33
return htmlEscapes[chr];
34
}
35
36
/**
37
* Converts the characters "&", "<", ">", '"', "'", and '`', in `string` to
38
* their corresponding HTML entities.
39
*
40
* **Note:** No other characters are escaped. To escape additional characters
41
* use a third-party library like [_he_](https://mths.be/he).
42
*
43
* Though the ">" character is escaped for symmetry, characters like
44
* ">" and "/" don't require escaping in HTML and have no special meaning
45
* unless they're part of a tag or unquoted attribute value.
46
* See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
47
* (under "semi-related fun fact") for more details.
48
*
49
* Backticks are escaped because in Internet Explorer < 9, they can break out
50
* of attribute values or HTML comments. See [#102](https://html5sec.org/#102),
51
* [#108](https://html5sec.org/#108), and [#133](https://html5sec.org/#133) of
52
* the [HTML5 Security Cheatsheet](https://html5sec.org/) for more details.
53
*
54
* When working with HTML you should always quote attribute values to reduce
55
* XSS vectors. See [Ryan Grove's article](http://wonko.com/post/html-escaping)
56
* for more details.
57
*
58
* @static
59
* @memberOf _
60
* @category String
61
* @param {string} [string=''] The string to escape.
62
* @returns {string} Returns the escaped string.
63
* @example
64
*
65
* _.escape('fred, barney, & pebbles');
66
* // => 'fred, barney, &amp; pebbles'
67
*/
68
function escape(string) {
69
// Reset `lastIndex` because in IE < 9 `String#replace` does not.
70
string = baseToString(string);
71
return (string && reHasUnescapedHtml.test(string))
72
? string.replace(reUnescapedHtml, escapeHtmlChar)
73
: string;
74
}
75
76
module.exports = escape;
77
78