chalk/source/utilities.js

34 lines
997 B
JavaScript
Raw Normal View History

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) {
2019-07-12 09:40:23 +03:00
let index = string.indexOf(substring);
if (index === -1) {
return string;
}
2019-07-12 13:59:50 +07:00
const substringLength = substring.length;
let endIndex = 0;
let returnValue = '';
2019-07-12 09:40:23 +03:00
do {
returnValue += string.slice(endIndex, index) + substring + replacer;
2019-07-12 13:59:50 +07:00
endIndex = index + substringLength;
index = string.indexOf(substring, 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
}
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';
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
}