Created
November 14, 2014 03:37
-
-
Save qi7chen/e6ca10a650ed3f1cd16a to your computer and use it in GitHub Desktop.
strip json comments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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++; | |
| ret += currentChar; | |
| ret += nextChar; | |
| continue; | |
| } 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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment