strip-json-comments.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*!
  2. strip-json-comments
  3. Strip comments from JSON. Lets you use comments in your JSON files!
  4. https://github.com/sindresorhus/strip-json-comments
  5. by Sindre Sorhus
  6. MIT License
  7. */
  8. (function () {
  9. 'use strict';
  10. var singleComment = 1;
  11. var multiComment = 2;
  12. function stripJsonComments(str) {
  13. var currentChar;
  14. var nextChar;
  15. var insideString = false;
  16. var insideComment = false;
  17. var ret = '';
  18. for (var i = 0; i < str.length; i++) {
  19. currentChar = str[i];
  20. nextChar = str[i + 1];
  21. if (!insideComment && currentChar === '"') {
  22. var escaped = str[i - 1] === '\\' && str[i - 2] !== '\\';
  23. if (!insideComment && !escaped && currentChar === '"') {
  24. insideString = !insideString;
  25. }
  26. }
  27. if (insideString) {
  28. ret += currentChar;
  29. continue;
  30. }
  31. if (!insideComment && currentChar + nextChar === '//') {
  32. insideComment = singleComment;
  33. i++;
  34. } else if (insideComment === singleComment && currentChar + nextChar === '\r\n') {
  35. insideComment = false;
  36. i++;
  37. ret += currentChar;
  38. ret += nextChar;
  39. continue;
  40. } else if (insideComment === singleComment && currentChar === '\n') {
  41. insideComment = false;
  42. } else if (!insideComment && currentChar + nextChar === '/*') {
  43. insideComment = multiComment;
  44. i++;
  45. continue;
  46. } else if (insideComment === multiComment && currentChar + nextChar === '*/') {
  47. insideComment = false;
  48. i++;
  49. continue;
  50. }
  51. if (insideComment) {
  52. continue;
  53. }
  54. ret += currentChar;
  55. }
  56. return ret;
  57. }
  58. if (typeof module !== 'undefined' && module.exports) {
  59. module.exports = stripJsonComments;
  60. } else {
  61. window.stripJsonComments = stripJsonComments;
  62. }
  63. })();