/
stripCmt.js
80 lines (70 loc) · 1.97 KB
/
stripCmt.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/* Strip comments from source code.
*
* |Name |Desc |
* |------|---------------------|
* |str |Source code |
* |return|Code without comments|
*/
/* example
* stripCmt('// comment \n var a = 5; \/* comment2\n * comment3\n *\/'); // -> ' var a = 5; '
*/
/* module
* env: all
*/
/* typescript
* export declare function stripCmt(str: string): string;
*/
exports = function(str) {
str = ('__' + str + '__').split('');
const mode = {
singleQuote: false,
doubleQuote: false,
regex: false,
blockComment: false,
lineComment: false,
condComp: false
};
for (let i = 0, l = str.length; i < l; i++) {
if (mode.regex) {
if (str[i] === '/' && str[i - 1] !== '\\') mode.regex = false;
continue;
}
if (mode.singleQuote) {
if (str[i] === "'" && str[i - 1] !== '\\') mode.singleQuote = false;
continue;
}
if (mode.doubleQuote) {
if (str[i] === '"' && str[i - 1] !== '\\') mode.doubleQuote = false;
continue;
}
if (mode.blockComment) {
if (str[i] === '*' && str[i + 1] === '/') {
str[i + 1] = '';
mode.blockComment = false;
}
str[i] = '';
continue;
}
if (mode.lineComment) {
if (str[i + 1] === '\n') mode.lineComment = false;
str[i] = '';
continue;
}
mode.doubleQuote = str[i] === '"';
mode.singleQuote = str[i] === "'";
if (str[i] === '/') {
if (str[i + 1] === '*') {
str[i] = '';
mode.blockComment = true;
continue;
}
if (str[i + 1] === '/') {
str[i] = '';
mode.lineComment = true;
continue;
}
mode.regex = true;
}
}
return str.join('').slice(2, -2);
};