utilities.js 997 B

123456789101112131415161718192021222324252627282930313233
  1. // TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.
  2. export function 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.slice(endIndex, index) + substring + replacer;
  12. endIndex = index + substringLength;
  13. index = string.indexOf(substring, endIndex);
  14. } while (index !== -1);
  15. returnValue += string.slice(endIndex);
  16. return returnValue;
  17. }
  18. export function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
  19. let endIndex = 0;
  20. let returnValue = '';
  21. do {
  22. const gotCR = string[index - 1] === '\r';
  23. returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
  24. endIndex = index + 1;
  25. index = string.indexOf('\n', endIndex);
  26. } while (index !== -1);
  27. returnValue += string.slice(endIndex);
  28. return returnValue;
  29. }