2021-11-26 16:50:15 +07:00
|
|
|
// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.
|
2021-04-16 15:23:29 +07:00
|
|
|
export function stringReplaceAll(string, substring, replacer) {
|
2026-03-17 11:25:21 +01:00
|
|
|
const index = string.indexOf(substring);
|
2019-07-12 09:40:23 +03:00
|
|
|
if (index === -1) {
|
|
|
|
|
return string;
|
|
|
|
|
}
|
|
|
|
|
|
2019-07-12 13:59:50 +07:00
|
|
|
const substringLength = substring.length;
|
2026-03-17 11:25:21 +01:00
|
|
|
const replacement = substring + replacer;
|
|
|
|
|
let result = '';
|
|
|
|
|
let lastIndex = 0;
|
|
|
|
|
let currentIndex = index;
|
|
|
|
|
|
2019-07-12 09:40:23 +03:00
|
|
|
do {
|
2026-03-17 11:25:21 +01:00
|
|
|
result += string.slice(lastIndex, currentIndex) + replacement;
|
|
|
|
|
lastIndex = currentIndex + substringLength;
|
|
|
|
|
currentIndex = string.indexOf(substring, lastIndex);
|
|
|
|
|
} while (currentIndex !== -1);
|
2019-07-12 09:40:23 +03:00
|
|
|
|
2026-03-17 11:25:21 +01:00
|
|
|
result += string.slice(lastIndex);
|
|
|
|
|
return result;
|
2021-04-16 15:23:29 +07:00
|
|
|
}
|
2019-07-12 09:40:23 +03:00
|
|
|
|
2021-04-16 15:23:29 +07:00
|
|
|
export function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
|
2019-07-12 13:59:50 +07:00
|
|
|
let endIndex = 0;
|
|
|
|
|
let returnValue = '';
|
2019-07-12 09:40:23 +03:00
|
|
|
do {
|
|
|
|
|
const gotCR = string[index - 1] === '\r';
|
2022-03-27 20:11:02 +02:00
|
|
|
returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
|
2019-07-12 13:59:50 +07:00
|
|
|
endIndex = index + 1;
|
|
|
|
|
index = string.indexOf('\n', endIndex);
|
2019-07-12 09:40:23 +03:00
|
|
|
} while (index !== -1);
|
|
|
|
|
|
2021-04-16 15:23:29 +07:00
|
|
|
returnValue += string.slice(endIndex);
|
2019-07-12 13:59:50 +07:00
|
|
|
return returnValue;
|
2021-04-16 15:23:29 +07:00
|
|
|
}
|