1
|
var escapeHtmlChar = require('./_escapeHtmlChar'),
|
2
|
toString = require('./toString');
|
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 their
|
10
|
* corresponding HTML entities.
|
11
|
*
|
12
|
* **Note:** No other characters are escaped. To escape additional
|
13
|
* characters 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. See
|
18
|
* [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
|
19
|
* (under "semi-related fun fact") for more details.
|
20
|
*
|
21
|
* When working with HTML you should always
|
22
|
* [quote attribute values](http://wonko.com/post/html-escaping) to reduce
|
23
|
* XSS vectors.
|
24
|
*
|
25
|
* @static
|
26
|
* @since 0.1.0
|
27
|
* @memberOf _
|
28
|
* @category String
|
29
|
* @param {string} [string=''] The string to escape.
|
30
|
* @returns {string} Returns the escaped string.
|
31
|
* @example
|
32
|
*
|
33
|
* _.escape('fred, barney, & pebbles');
|
34
|
* // => 'fred, barney, & pebbles'
|
35
|
*/
|
36
|
function escape(string) {
|
37
|
string = toString(string);
|
38
|
return (string && reHasUnescapedHtml.test(string))
|
39
|
? string.replace(reUnescapedHtml, escapeHtmlChar)
|
40
|
: string;
|
41
|
}
|
42
|
|
43
|
module.exports = escape;
|