/
strTrim.ts
58 lines (51 loc) · 1.79 KB
/
strTrim.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import escapeRegExp from './utils/escapeRegExp.js';
export const STR_TRIM_LEFT = 'left';
export const STR_TRIM_RIGHT = 'right';
export const STR_TRIM_BOTH = 'both';
export const STR_TRIM_CHARS = [' ', '\t', '\r', '\n', '\r\n', '\f', '\v', '\0'];
/**
* Trim the string of the given characters.
*
* @param {string} value - The target string
* @param {string | string[]} [characters=[' ', '\t', '\r', '\n', '\r\n', '\f', '\v', '\0']] - The characters to be trimmed off
* @param {'left' | 'right' | 'both'} [side='both'] - The side of a string to be trimmed off
* @returns {string}
*
* @example
* ```js
* strTrim(' yolo '); // 'yolo'
* strTrim('/yolo/', '/'); // 'yolo'
* ```
*/
export default function strTrim(
value: string,
characters: string | string[] = STR_TRIM_CHARS,
side: string = STR_TRIM_BOTH
): string {
if (typeof characters === 'string') {
characters = [characters];
}
if (characters.length > 1) {
/**
* Say "characters" is equal to "[' ', '_']"
* -> [...characters, ...characters.reverse()] --> "[' ', '_', '_', ' ']"
* -> [...characters, ...characters.reverse().slice(1)] --> "[' ', '_', ' ']"
*/
characters = [...characters, ...characters.reverse().slice(1)];
}
return characters.reduce((acc, character) => {
acc = acc.replace(new RegExp(_regExpStr(character, side), 'g'), '');
return acc;
}, value + '');
}
function _regExpStr(character: string, side: string): string {
switch (side) {
case STR_TRIM_LEFT:
return `(^${escapeRegExp(character)}+)`;
case STR_TRIM_RIGHT:
return `(${escapeRegExp(character)}+$)`;
case STR_TRIM_BOTH:
default:
return `(^${escapeRegExp(character)}+)|(${escapeRegExp(character)}+$)`;
}
}