index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. var singleComment = 1;
  3. var multiComment = 2;
  4. function stripWithoutWhitespace() {
  5. return '';
  6. }
  7. function stripWithWhitespace(str, start, end) {
  8. return str.slice(start, end).replace(/\S/g, ' ');
  9. }
  10. module.exports = function (str, opts) {
  11. opts = opts || {};
  12. var currentChar;
  13. var nextChar;
  14. var insideString = false;
  15. var insideComment = false;
  16. var offset = 0;
  17. var ret = '';
  18. var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;
  19. for (var i = 0; i < str.length; i++) {
  20. currentChar = str[i];
  21. nextChar = str[i + 1];
  22. if (!insideComment && currentChar === '"') {
  23. var escaped = str[i - 1] === '\\' && str[i - 2] !== '\\';
  24. if (!escaped) {
  25. insideString = !insideString;
  26. }
  27. }
  28. if (insideString) {
  29. continue;
  30. }
  31. if (!insideComment && currentChar + nextChar === '//') {
  32. ret += str.slice(offset, i);
  33. offset = i;
  34. insideComment = singleComment;
  35. i++;
  36. } else if (insideComment === singleComment && currentChar + nextChar === '\r\n') {
  37. i++;
  38. insideComment = false;
  39. ret += strip(str, offset, i);
  40. offset = i;
  41. continue;
  42. } else if (insideComment === singleComment && currentChar === '\n') {
  43. insideComment = false;
  44. ret += strip(str, offset, i);
  45. offset = i;
  46. } else if (!insideComment && currentChar + nextChar === '/*') {
  47. ret += str.slice(offset, i);
  48. offset = i;
  49. insideComment = multiComment;
  50. i++;
  51. continue;
  52. } else if (insideComment === multiComment && currentChar + nextChar === '*/') {
  53. i++;
  54. insideComment = false;
  55. ret += strip(str, offset, i + 1);
  56. offset = i + 1;
  57. continue;
  58. }
  59. }
  60. return ret + (insideComment ? strip(str.substr(offset)) : str.substr(offset));
  61. };