1
|
/*!
|
2
|
* escape-html
|
3
|
* Copyright(c) 2012-2013 TJ Holowaychuk
|
4
|
* Copyright(c) 2015 Andreas Lubbe
|
5
|
* Copyright(c) 2015 Tiancheng "Timothy" Gu
|
6
|
* MIT Licensed
|
7
|
*/
|
8
|
|
9
|
'use strict';
|
10
|
|
11
|
/**
|
12
|
* Module variables.
|
13
|
* @private
|
14
|
*/
|
15
|
|
16
|
var matchHtmlRegExp = /["'&<>]/;
|
17
|
|
18
|
/**
|
19
|
* Module exports.
|
20
|
* @public
|
21
|
*/
|
22
|
|
23
|
module.exports = escapeHtml;
|
24
|
|
25
|
/**
|
26
|
* Escape special characters in the given string of html.
|
27
|
*
|
28
|
* @param {string} string The string to escape for inserting into HTML
|
29
|
* @return {string}
|
30
|
* @public
|
31
|
*/
|
32
|
|
33
|
function escapeHtml(string) {
|
34
|
var str = '' + string;
|
35
|
var match = matchHtmlRegExp.exec(str);
|
36
|
|
37
|
if (!match) {
|
38
|
return str;
|
39
|
}
|
40
|
|
41
|
var escape;
|
42
|
var html = '';
|
43
|
var index = 0;
|
44
|
var lastIndex = 0;
|
45
|
|
46
|
for (index = match.index; index < str.length; index++) {
|
47
|
switch (str.charCodeAt(index)) {
|
48
|
case 34: // "
|
49
|
escape = '"';
|
50
|
break;
|
51
|
case 38: // &
|
52
|
escape = '&';
|
53
|
break;
|
54
|
case 39: // '
|
55
|
escape = ''';
|
56
|
break;
|
57
|
case 60: // <
|
58
|
escape = '<';
|
59
|
break;
|
60
|
case 62: // >
|
61
|
escape = '>';
|
62
|
break;
|
63
|
default:
|
64
|
continue;
|
65
|
}
|
66
|
|
67
|
if (lastIndex !== index) {
|
68
|
html += str.substring(lastIndex, index);
|
69
|
}
|
70
|
|
71
|
lastIndex = index + 1;
|
72
|
html += escape;
|
73
|
}
|
74
|
|
75
|
return lastIndex !== index
|
76
|
? html + str.substring(lastIndex, index)
|
77
|
: html;
|
78
|
}
|