smartstring/ts/smartstring.normalize.ts
2023-08-31 16:31:23 +02:00

52 lines
1.3 KiB
TypeScript

import * as plugins from './smartstring.plugins.js';
/**
* replaces all occurences of something in a string
* @param stringArg
* @param searchPattern
* @param replacementString
*/
export const replaceAll = (stringArg: string, searchPattern: string, replacementString: string) => {
return stringArg.replace(new RegExp(searchPattern, 'g'), replacementString);
};
export interface INormalizeOptions {
stripLeadingTrailingEmptyLines?: boolean;
stripAllEmptyLines?: boolean;
stripIndent?: boolean;
normalizeNewline?: boolean;
replaceTabs?: boolean;
}
/**
* Normalizes a string
* @param stringArg
* @param options
*/
export const standard = (stringArg: string, options?: INormalizeOptions): string => {
let result = stringArg;
if (!options || options.stripIndent) {
result = plugins.stripIndent(result); // fix indention
}
if (!options || options.normalizeNewline) {
result = plugins.normalizeNewline(result); // fix newlines
}
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;
};