Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80742 views
1
var baseToString = require('../internal/baseToString'),
2
escapeHtmlChar = require('../internal/escapeHtmlChar');
3
4
/** Used to match HTML entities and HTML characters. */
5
var reUnescapedHtml = /[&<>"'`]/g,
6
reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
7
8
/**
9
* Converts the characters "&", "<", ">", '"', "'", and "\`", in `string` to
10
* their corresponding HTML entities.
11
*
12
* **Note:** No other characters are escaped. To escape additional characters
13
* use a third-party library like [_he_](https://mths.be/he).
14
*
15
* Though the ">" character is escaped for symmetry, characters like
16
* ">" and "/" don't need escaping in HTML and have no special meaning
17
* unless they're part of a tag or unquoted attribute value.
18
* See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
19
* (under "semi-related fun fact") for more details.
20
*
21
* Backticks are escaped because in Internet Explorer < 9, they can break out
22
* of attribute values or HTML comments. See [#59](https://html5sec.org/#59),
23
* [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and
24
* [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/)
25
* for more details.
26
*
27
* When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping)
28
* to reduce XSS vectors.
29
*
30
* @static
31
* @memberOf _
32
* @category String
33
* @param {string} [string=''] The string to escape.
34
* @returns {string} Returns the escaped string.
35
* @example
36
*
37
* _.escape('fred, barney, & pebbles');
38
* // => 'fred, barney, &amp; pebbles'
39
*/
40
function escape(string) {
41
// Reset `lastIndex` because in IE < 9 `String#replace` does not.
42
string = baseToString(string);
43
return (string && reHasUnescapedHtml.test(string))
44
? string.replace(reUnescapedHtml, escapeHtmlChar)
45
: string;
46
}
47
48
module.exports = escape;
49
50