-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathutils-string.ts
91 lines (75 loc) · 2.06 KB
/
utils-string.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const COUCH_NAME_CHARS = 'abcdefghijklmnopqrstuvwxyz';
/**
* Get a random string which can be used for many things in RxDB.
* The returned string is guaranteed to be a valid database name or collection name
* and also to be a valid JavaScript variable name.
*
* @link http://stackoverflow.com/a/1349426/3443137
*/
export function randomToken(length: number = 10): string {
let text = '';
for (let i = 0; i < length; i++) {
text += COUCH_NAME_CHARS.charAt(Math.floor(Math.random() * COUCH_NAME_CHARS.length));
}
return text;
}
/**
* A random string that is never inside of any storage
*/
export const RANDOM_STRING = 'Fz7SZXPmYJujkzjY1rpXWvlWBqoGAfAX';
/**
* uppercase first char
*/
export function ucfirst(str: string): string {
str += '';
const f = str.charAt(0)
.toUpperCase();
return f + str.substr(1);
}
/**
* removes trailing and ending dots from the string
*/
export function trimDots(str: string): string {
// start
while (str.charAt(0) === '.') {
str = str.substr(1);
}
// end
while (str.slice(-1) === '.') {
str = str.slice(0, -1);
}
return str;
}
/**
* @link https://stackoverflow.com/a/44950500/3443137
*/
export function lastCharOfString(str: string): string {
return str.charAt(str.length - 1);
}
/**
* returns true if the given name is likely a folder path
*/
export function isFolderPath(name: string) {
// do not check, if foldername is given
if (
name.includes('/') || // unix
name.includes('\\') // windows
) {
return true;
} else {
return false;
}
}
/**
* @link https://gist.github.com/andreburgaud/6f73fd2d690b629346b8
* @link https://stackoverflow.com/a/76240378/3443137
*/
export function arrayBufferToString(arrayBuffer: ArrayBuffer): string {
return new TextDecoder().decode(arrayBuffer);
}
export function stringToArrayBuffer(str: string): ArrayBuffer {
return new TextEncoder().encode(str);
}
export function normalizeString(str: string): string {
return str.trim().replace(/[\n\s]+/g, '');
}