Skip to content

Instantly share code, notes, and snippets.

@qi7chen
Created November 14, 2014 03:37
Show Gist options
  • Select an option

  • Save qi7chen/e6ca10a650ed3f1cd16a to your computer and use it in GitHub Desktop.

Select an option

Save qi7chen/e6ca10a650ed3f1cd16a to your computer and use it in GitHub Desktop.
strip json comments
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