smartstring/ts/smartstring.normalize.ts

52 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-03-18 21:50:24 +00:00
import * as plugins from './smartstring.plugins.js';
2017-10-05 13:55:59 +00:00
/**
* replaces all occurences of something in a string
* @param stringArg
2019-01-12 19:19:16 +00:00
* @param searchPattern
* @param replacementString
2017-10-05 13:55:59 +00:00
*/
2019-01-12 19:19:16 +00:00
export const replaceAll = (stringArg: string, searchPattern: string, replacementString: string) => {
return stringArg.replace(new RegExp(searchPattern, 'g'), replacementString);
};
2017-10-05 13:55:59 +00:00
2023-08-31 14:31:23 +00:00
export interface INormalizeOptions {
stripLeadingTrailingEmptyLines?: boolean;
stripAllEmptyLines?: boolean;
stripIndent?: boolean;
normalizeNewline?: boolean;
replaceTabs?: boolean;
}
2017-10-05 13:55:59 +00:00
/**
2023-08-31 14:31:23 +00:00
* Normalizes a string
2017-10-05 13:55:59 +00:00
* @param stringArg
2023-08-31 14:31:23 +00:00
* @param options
2017-10-05 13:55:59 +00:00
*/
2023-08-31 14:31:23 +00:00
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) {
2024-03-01 22:34:43 +00:00
result = result.replace(/\r\n/g, '\n'); // fix newlines
2023-08-31 14:31:23 +00: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 14:31:23 +00:00