Files
smartstring/ts/smartstring.normalize.ts

82 lines
2.0 KiB
TypeScript
Raw Permalink Normal View History

2017-10-05 15:55:59 +02:00
/**
* replaces all occurences of something in a string
* @param stringArg
2019-01-12 20:19:16 +01:00
* @param searchPattern
* @param replacementString
2017-10-05 15:55:59 +02:00
*/
2019-01-12 20:19:16 +01:00
export const replaceAll = (stringArg: string, searchPattern: string, replacementString: string) => {
return stringArg.replace(new RegExp(searchPattern, 'g'), replacementString);
};
2017-10-05 15:55:59 +02:00
/**
* Custom implementation of strip-indent
* Removes the minimum indentation from all lines
*/
const stripIndent = (str: string): string => {
const lines = str.split('\n');
// Find the minimum indentation (ignoring empty lines)
let minIndent = Infinity;
for (const line of lines) {
if (line.trim().length > 0) {
const match = line.match(/^(\s*)/);
if (match) {
minIndent = Math.min(minIndent, match[1].length);
}
}
}
// If no indentation found, return original string
if (minIndent === Infinity || minIndent === 0) {
return str;
}
// Remove the minimum indentation from all lines
return lines.map(line => {
if (line.length >= minIndent) {
return line.slice(minIndent);
}
return line;
}).join('\n');
};
2023-08-31 16:31:23 +02:00
export interface INormalizeOptions {
stripLeadingTrailingEmptyLines?: boolean;
stripAllEmptyLines?: boolean;
stripIndent?: boolean;
normalizeNewline?: boolean;
replaceTabs?: boolean;
}
2017-10-05 15:55:59 +02:00
/**
2023-08-31 16:31:23 +02:00
* Normalizes a string
2017-10-05 15:55:59 +02:00
* @param stringArg
2023-08-31 16:31:23 +02:00
* @param options
2017-10-05 15:55:59 +02:00
*/
2023-08-31 16:31:23 +02:00
export const standard = (stringArg: string, options?: INormalizeOptions): string => {
let result = stringArg;
if (!options || options.stripIndent) {
result = stripIndent(result); // fix indention
2023-08-31 16:31:23 +02:00
}
if (!options || options.normalizeNewline) {
2024-03-01 23:34:43 +01:00
result = result.replace(/\r\n/g, '\n'); // fix newlines
2023-08-31 16:31:23 +02:00
}
if (!options || options.replaceTabs) {
result = replaceAll(result, '\t/', ' '); // fix tabs
}
if (!options || options.stripLeadingTrailingEmptyLines) {
result = result.replace(/^\s*[\r\n]/gm, '').replace(/\s*[\r\n]$/gm, '');
}
if (!options || options.stripAllEmptyLines) {
result = result.replace(/^\s*[\r\n]/gm, '');
}
return result;
};
2023-08-31 16:31:23 +02:00