1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | 'use strict';
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | var matchHtmlRegExp = /["'&<>]/;
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | module.exports = escapeHtml;
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
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 | }
|