forked from sindresorhus/strip-json-comments
-
Notifications
You must be signed in to change notification settings - Fork 0
/
strip-json-comments.js
64 lines (55 loc) · 1.41 KB
/
strip-json-comments.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
/*!
strip-json-comments
Strip comments from JSON. Lets you use comments in your JSON files!
https://github.com/sindresorhus/strip-json-comments
by Sindre Sorhus
MIT License
*/
(function () {
'use strict';
function stripJsonComments(str) {
var currentChar;
var nextChar;
var insideString = false;
var insideComment = false;
var ret = '';
for (var i = 0; i < str.length; i++) {
currentChar = str[i];
nextChar = str[i + 1];
if (!insideComment && str[i - 1] !== '\\' && currentChar === '"') {
insideString = !insideString;
}
if (insideString) {
ret += currentChar;
continue;
}
if (!insideComment && currentChar + nextChar === '//') {
insideComment = 'single';
i++;
} else if (insideComment === 'single' && currentChar + nextChar === '\r\n') {
insideComment = false;
i++;
} else if (insideComment === 'single' && currentChar === '\n') {
insideComment = false;
} else if (!insideComment && currentChar + nextChar === '/*') {
insideComment = 'multi';
i++;
continue;
} else if (insideComment === 'multi' && currentChar + nextChar === '*/') {
insideComment = false;
i++;
continue;
}
if (insideComment) {
continue;
}
ret += currentChar;
}
return ret;
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = stripJsonComments;
} else {
window.stripJsonComments = stripJsonComments;
}
})();