-
Notifications
You must be signed in to change notification settings - Fork 268
/
Copy pathstring.js
338 lines (269 loc) · 7.41 KB
/
string.js
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
export function camelToTitle(str) {
return dasherize((str || '')).split('-').map((str) => {
return ucFirst(str);
}).join(' ');
}
export function ucFirst(str) {
str = str || '';
return str.substr(0, 1).toUpperCase() + str.substr(1);
}
export function lcFirst(str) {
str = str || '';
return str.substr(0, 1).toLowerCase() + str.substr(1);
}
export function strPad(str, toLength, padChars = ' ', right = false) {
str = `${ str }`;
if (str.length >= toLength) {
return str;
}
const neededLen = toLength - str.length + 1;
const padStr = (new Array(neededLen)).join(padChars).substr(0, neededLen);
if (right) {
return str + padStr;
} else {
return padStr + str;
}
}
// Turn thing1 into thing00000001 so that the numbers sort numerically
export function sortableNumericSuffix(str) {
str = str || '';
const match = str.match(/^(.*[^0-9])([0-9]+)$/);
if (match) {
return match[1] + strPad(match[2], 8, '0');
}
return str;
}
const entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
};
export function escapeHtml(html) {
return String(html).replace(/[&<>"']/g, (s) => {
return entityMap[s];
});
}
/**
* Return HTML markup from escaped HTML string, allowing specific tags
* @param text string
* @returns string
*/
export function decodeHtml(text) {
const div = document.createElement('div');
div.innerHTML = text;
return div.textContent || div.innerText || '';
}
export function escapeRegex(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
export function random32(count) {
count = Math.max(0, count || 1);
const out = [];
let i;
if (window.crypto && window.crypto.getRandomValues) {
const tmp = new Uint32Array(count);
window.crypto.getRandomValues(tmp);
for (i = 0; i < tmp.length; i++) {
out[i] = tmp[i];
}
} else {
for (i = 0; i < count; i++) {
out[i] = Math.random() * 4294967296; // Math.pow(2,32);
}
}
if (count === 1) {
return out[0];
} else {
return out;
}
}
const alpha = 'abcdefghijklmnopqrstuvwxyz';
const num = '0123456789';
const sym = '!@#$%^&*()_+-=[]{};:,./<>?|';
export const CHARSET = {
NUMERIC: num,
NO_VOWELS: 'bcdfghjklmnpqrstvwxz2456789',
ALPHA: alpha + alpha.toUpperCase(),
ALPHA_NUM: alpha + alpha.toUpperCase() + num,
ALPHA_LOWER: alpha,
ALPHA_UPPER: alpha.toUpperCase(),
HEX: `${ num }ABCDEF`,
PASSWORD: alpha + alpha.toUpperCase() + num + alpha + alpha.toUpperCase() + num + sym,
// ^-- includes alpha / ALPHA / num twice to reduce the occurrence of symbols
};
export function randomStr(length = 16, chars = CHARSET.ALPHA_NUM) {
if (!chars || !chars.length) {
return null;
}
return random32(length).map((val) => {
return chars[val % chars.length];
}).join('');
}
export function formatPercent(value, maxPrecision = 2) {
if (value < 1 && maxPrecision >= 2) {
return `${ Math.round(value * 100) / 100 }%`;
} else if (value < 10 && maxPrecision >= 1) {
return `${ Math.round(value * 10) / 10 }%`;
} else {
return `${ Math.round(value) }%`;
}
}
export function pluralize(str) {
if ( str.match(/.*[^aeiou]y$/i) ) {
return `${ str.substr(0, str.length - 1) }ies`;
} else if ( str.endsWith('ics') ) {
return str;
} else if ( str.endsWith('s') ) {
return `${ str }es`;
} else {
return `${ str }s`;
}
}
export function resourceNames(names, plusMore, t) {
return names.reduce((res, name, i) => {
if (i >= 5) {
return res;
}
res += `<b>${ escapeHtml( name ) }</b>`;
if (i === names.length - 1) {
res += plusMore;
} else {
res += i === names.length - 2 ? t('generic.and') : t('generic.comma');
}
return res;
}, '');
}
export function indent(lines, count = 2, token = ' ', afterRegex = null) {
if (typeof lines === 'string') {
lines = lines.split(/\n/);
} else {
lines = lines || [];
}
const padStr = (new Array(count + 1)).join(token);
const out = lines.map((line) => {
let prefix = '';
let suffix = line;
if (afterRegex) {
const match = line.match(afterRegex);
if (match) {
prefix = match[match.length - 1];
suffix = line.substr(match[0].length);
}
}
return `${ prefix }${ padStr }${ suffix }`;
});
const str = out.join('\n');
return str;
}
const decamelizeRegex = /([a-z\d])([A-Z])/g;
export function decamelize(str) {
return str.replace(decamelizeRegex, '$1_$2').toLowerCase();
}
const dasherizeRegex = /[ _]/g;
export function dasherize(str) {
return decamelize(str).replace(dasherizeRegex, '-');
}
export function asciiLike(str) {
str = str || '';
if ( str.match(/[^\r\n\t\x20-\x7F]/) ) {
return false;
}
return true;
}
export function coerceStringTypeToScalarType(val, type) {
if ( type === 'float' ) {
// Coerce strings to floats
val = parseFloat(val) || null; // NaN becomes null
} else if ( type === 'int' ) {
// Coerce strings to ints
val = parseInt(val, 10);
if ( isNaN(val) ) {
val = null;
}
} else if ( type === 'boolean') {
// Coerce strings to boolean
if (val.toLowerCase() === 'true') {
val = true;
} else if (val.toLowerCase() === 'false') {
val = false;
}
}
return val;
}
export function matchesSomeRegex(stringRaw, regexes = []) {
return regexes.some((regexRaw) => {
const string = stringRaw || '';
const regex = ensureRegex(regexRaw);
return string.match(regex);
});
}
export function ensureRegex(strOrRegex, exact = true) {
if ( typeof strOrRegex === 'string' ) {
if ( exact ) {
return new RegExp(`^${ escapeRegex(strOrRegex) }$`, 'i');
} else {
return new RegExp(`${ escapeRegex(strOrRegex) }`, 'i');
}
}
return strOrRegex;
}
export function nlToBr(value) {
return escapeHtml(value || '').replace(/(\r\n|\r|\n)/g, '<br/>\n');
}
const quotedMatch = /[^."']+|"([^"]*)"|'([^']*)'/g;
export function splitObjectPath(path) {
if ( path.includes('"') || path.includes("'") ) {
// Path with quoted section
return path.match(quotedMatch).map((x) => x.replace(/['"]/g, ''));
}
// Regular path
return path.split('.');
}
export function joinObjectPath(ary) {
let out = '';
for ( const p of ary ) {
if ( p.includes('.') ) {
out += `."${ p }"`;
} else {
out += `.${ p }`;
}
}
if ( out.startsWith('.') ) {
out = out.substr(1);
}
return out;
}
export function shortenedImage(image) {
return (image || '')
.replace(/^(index\.)?docker.io\/(library\/)?/, '')
.replace(/:latest$/, '')
.replace(/^(.*@sha256:)([0-9a-f]{8})[0-9a-f]+$/i, '$1$2…');
}
export function isIpv4(ip) {
const reg = /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/;
return reg.test(ip);
}
export function sanitizeKey(k) {
return (k || '').replace(/[^a-z0-9./_-]/ig, '');
}
export function sanitizeValue(v) {
return (v || '').replace(/[^a-z0-9._-]/ig, '');
}
export function sanitizeIP(v) {
return (v || '').replace(/[^a-z0-9.:_-]/ig, '');
}
/**
* Return the string `<x> / <y>`
*
* Each param should be a number, otherwise `?` is used
*/
export function xOfy(x, y) {
return `${ typeof x === 'number' ? x : '?' }/${ typeof y === 'number' ? y : '?' }`;
}
export function isBase64(value) {
const base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
return base64regex.test(value);
}