util.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. const stringReplaceAll = (string, substring, replacer) => {
  3. let index = string.indexOf(substring);
  4. if (index === -1) {
  5. return string;
  6. }
  7. const substringLength = substring.length;
  8. let endIndex = 0;
  9. let returnValue = '';
  10. do {
  11. returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
  12. endIndex = index + substringLength;
  13. index = string.indexOf(substring, endIndex);
  14. } while (index !== -1);
  15. returnValue += string.substr(endIndex);
  16. return returnValue;
  17. };
  18. const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
  19. let endIndex = 0;
  20. let returnValue = '';
  21. do {
  22. const gotCR = string[index - 1] === '\r';
  23. returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
  24. endIndex = index + 1;
  25. index = string.indexOf('\n', endIndex);
  26. } while (index !== -1);
  27. returnValue += string.substr(endIndex);
  28. return returnValue;
  29. };
  30. module.exports = {
  31. stringReplaceAll,
  32. stringEncaseCRLFWithFirstIndex
  33. };