UNPKG

super-utils-plus

Version:

A superior alternative to Lodash with improved performance, TypeScript support, and developer experience

93 lines (92 loc) 2.17 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.trim = trim; exports.trimStart = trimStart; exports.trimEnd = trimEnd; /** * Removes leading and trailing whitespace or specified characters from string. * * @param string - The string to trim * @param chars - The characters to trim * @returns The trimmed string * * @example * ```ts * trim(' abc '); * // => 'abc' * * trim('-_-abc-_-', '_-'); * // => 'abc' * ``` */ function trim(string, chars) { if (!string) { return ''; } if (!chars) { return string.trim(); } // Create a regex pattern with the chars to trim const pattern = new RegExp(`^[${escapeRegExp(chars)}]+|[${escapeRegExp(chars)}]+$`, 'g'); return string.replace(pattern, ''); } /** * Removes leading whitespace or specified characters from string. * * @param string - The string to trim * @param chars - The characters to trim * @returns The trimmed string * * @example * ```ts * trimStart(' abc '); * // => 'abc ' * * trimStart('-_-abc-_-', '_-'); * // => 'abc-_-' * ``` */ function trimStart(string, chars) { if (!string) { return ''; } if (!chars) { return string.trimStart(); } // Create a regex pattern with the chars to trim const pattern = new RegExp(`^[${escapeRegExp(chars)}]+`, 'g'); return string.replace(pattern, ''); } /** * Removes trailing whitespace or specified characters from string. * * @param string - The string to trim * @param chars - The characters to trim * @returns The trimmed string * * @example * ```ts * trimEnd(' abc '); * // => ' abc' * * trimEnd('-_-abc-_-', '_-'); * // => '-_-abc' * ``` */ function trimEnd(string, chars) { if (!string) { return ''; } if (!chars) { return string.trimEnd(); } // Create a regex pattern with the chars to trim const pattern = new RegExp(`[${escapeRegExp(chars)}]+$`, 'g'); return string.replace(pattern, ''); } /** * Escapes the RegExp special characters in a string. */ function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); }