• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.
2export function stringReplaceAll(string, substring, replacer) {
3	let index = string.indexOf(substring);
4	if (index === -1) {
5		return string;
6	}
7
8	const substringLength = substring.length;
9	let endIndex = 0;
10	let returnValue = '';
11	do {
12		returnValue += string.slice(endIndex, index) + substring + replacer;
13		endIndex = index + substringLength;
14		index = string.indexOf(substring, endIndex);
15	} while (index !== -1);
16
17	returnValue += string.slice(endIndex);
18	return returnValue;
19}
20
21export function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
22	let endIndex = 0;
23	let returnValue = '';
24	do {
25		const gotCR = string[index - 1] === '\r';
26		returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
27		endIndex = index + 1;
28		index = string.indexOf('\n', endIndex);
29	} while (index !== -1);
30
31	returnValue += string.slice(endIndex);
32	return returnValue;
33}
34