stripCmt.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. exports = function(str) {
  2. str = ('__' + str + '__').split('');
  3. var mode = {
  4. singleQuote: false,
  5. doubleQuote: false,
  6. regex: false,
  7. blockComment: false,
  8. lineComment: false,
  9. condComp: false
  10. };
  11. for (var i = 0, l = str.length; i < l; i++) {
  12. if (mode.regex) {
  13. if (str[i] === '/' && str[i - 1] !== '\\') mode.regex = false;
  14. continue;
  15. }
  16. if (mode.singleQuote) {
  17. if (str[i] === "'" && str[i - 1] !== '\\') mode.singleQuote = false;
  18. continue;
  19. }
  20. if (mode.doubleQuote) {
  21. if (str[i] === '"' && str[i - 1] !== '\\') mode.doubleQuote = false;
  22. continue;
  23. }
  24. if (mode.blockComment) {
  25. if (str[i] === '*' && str[i + 1] === '/') {
  26. str[i + 1] = '';
  27. mode.blockComment = false;
  28. }
  29. str[i] = '';
  30. continue;
  31. }
  32. if (mode.lineComment) {
  33. if (str[i + 1] === '\n') mode.lineComment = false;
  34. str[i] = '';
  35. continue;
  36. }
  37. mode.doubleQuote = str[i] === '"';
  38. mode.singleQuote = str[i] === "'";
  39. if (str[i] === '/') {
  40. if (str[i + 1] === '*') {
  41. str[i] = '';
  42. mode.blockComment = true;
  43. continue;
  44. }
  45. if (str[i + 1] === '/') {
  46. str[i] = '';
  47. mode.lineComment = true;
  48. continue;
  49. }
  50. mode.regex = true;
  51. }
  52. }
  53. return str.join('').slice(2, -2);
  54. };
  55. module.exports = exports;