fix: check version and use built in replace all
This commit is contained in:
parent
51557784b8
commit
c8ce91527f
1 changed files with 37 additions and 6 deletions
|
|
@ -1,5 +1,17 @@
|
|||
// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.
|
||||
const SUPPORTED_NODE_VER = 16;
|
||||
|
||||
export function stringReplaceAll(string, substring, replacer) {
|
||||
if (
|
||||
getVersion()?.major >= SUPPORTED_NODE_VER
|
||||
typeof String.prototype.replaceAll === "function" &&
|
||||
) {
|
||||
return string.replaceAll(substring, replacer);
|
||||
}
|
||||
|
||||
return _stringReplaceAllPolyfill(string, substring, replacer);
|
||||
}
|
||||
|
||||
function _stringReplaceAllPolyfill(string, substring, replacer) {
|
||||
let index = string.indexOf(substring);
|
||||
if (index === -1) {
|
||||
return string;
|
||||
|
|
@ -7,7 +19,7 @@ export function stringReplaceAll(string, substring, replacer) {
|
|||
|
||||
const substringLength = substring.length;
|
||||
let endIndex = 0;
|
||||
let returnValue = '';
|
||||
let returnValue = "";
|
||||
do {
|
||||
returnValue += string.slice(endIndex, index) + substring + replacer;
|
||||
endIndex = index + substringLength;
|
||||
|
|
@ -20,14 +32,33 @@ export function stringReplaceAll(string, substring, replacer) {
|
|||
|
||||
export function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
|
||||
let endIndex = 0;
|
||||
let returnValue = '';
|
||||
let returnValue = "";
|
||||
do {
|
||||
const gotCR = string[index - 1] === '\r';
|
||||
returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
|
||||
const gotCR = string[index - 1] === "\r";
|
||||
returnValue +=
|
||||
string.slice(endIndex, gotCR ? index - 1 : index) +
|
||||
prefix +
|
||||
(gotCR ? "\r\n" : "\n") +
|
||||
postfix;
|
||||
endIndex = index + 1;
|
||||
index = string.indexOf('\n', endIndex);
|
||||
index = string.indexOf("\n", endIndex);
|
||||
} while (index !== -1);
|
||||
|
||||
returnValue += string.slice(endIndex);
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
function getVersion() {
|
||||
const nodeVersion = process.version;
|
||||
if (!nodeVersion) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parts = nodeVersion.split(".");
|
||||
|
||||
return {
|
||||
major: parseInt(parts[0]),
|
||||
minor: parseInt(parts[1]),
|
||||
patch: parseInt(parts[2]),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue