-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrings.js
More file actions
453 lines (435 loc) · 17.7 KB
/
strings.js
File metadata and controls
453 lines (435 loc) · 17.7 KB
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
import pluralize from './pluralize/pluralize.js';
/**
* @module
*/
const Strings = {
/**
* Returns the english plural form of the given input string.
* @param {String} input - The value to be pluralized.
* @returns {String}
*/
plural(input) {
return pluralize.plural(input);
},
/**
* Returns the english singular form of the given input string.
* @param {String} input - The value to be made into it's singular form.
* @returns {String}
*/
singular(input) {
return pluralize.singular(input);
},
/**
* Performs a smart-split operation to split the string using any given separators and trimming whitespace for
* each value. This allows for mixed-inputs of separate values to be easily processed.
* Any empty values are omitted.
*
* @param {String} input - The string to be split.
* @param {Boolean} [trim=true] - Indicates whitespace should be removed from each split value (default = `true`).
* @param {...String} [separators] - Spread of seperating strings/characters. Defaults to `",", "\n", ";", "|"`.
* @returns {Array.<String>}
*/
ssplit(input, trim = true, ...separators) {
if (input === null) {
return null;
} else if (typeof input !== 'string') {
throw new Error('Argument for the paramater "input" is not a string or null value type.');
}
if (!separators || separators.length === 0) {
separators = [',', '\n', ';', '|'];
}
let results = separators.reduce((a, c, ci) => ci ? a.map(v => v.split(c)).flat() : input.split(c), []);
if (trim) {
for (let i = 0; i < results.length; i++) {
results[i] = results[i].replace(/^\s+/g, '').replace(/\s+$/g, '');
}
}
return results;
},
/**
* Attempts to parse a regular expression literal string, potentially including flags.
* @param {String|RegExp} input - The regular expression literal string.
* @returns {RegExp}
*/
toRegExp: function (input) {
if (input instanceof RegExp) {
return input;
}
if (typeof input === 'string') {
let firstSlash = input.indexOf('/');
let lastSlash = input.lastIndexOf('/');
let flags = null;
//check if the regexp is in literal format and may include flags
if (firstSlash === 0 && lastSlash > -1 && firstSlash !== lastSlash) {
//looks like a regex string with potential flags
flags = input.substr(lastSlash + 1);
//strip slashes.
input = input.substring(firstSlash + 1, lastSlash);
}
if (flags) {
return new RegExp(input, flags);
} else {
return new RegExp(input);
}
}
return null;
},
/**
* Escape a string value using the given method so it can be safely parsed.
* @param {String} input - The string value to escape.
* @param {Strings.EscapeMethod|Number} method - The escape method to use.
* @returns {String}
*/
escape: function (input, method) {
if (method == Strings.EscapeMethod.URI) {
return escape(input);
} else if (method === Strings.EscapeMethod.REGEXP) {
//eslint-disable-next-line no-useless-escape
return input.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
throw new Error('A valid "method" argument is reguired.');
},
/**
* Checks if the input string matches any one of the given test values.
* @param {String} input - The string to test for a match.
* @param {String|String[]|RegExp|RegExp[]} test - The string(s) or RegExp to test the input against.
* @param {Boolean} [insensitive=false] - If true, the test will be made case-insensitive.
* @returns {Boolean}
*/
some: function (input, test, insensitive) {
if (typeof input === 'undefined') {
return false;
} else if (input === null && input === test) {
return true;
}
if (Array.isArray(test) === false) {
test = [test];
}
for (let t of test) {
if (typeof t === 'string') {
if (input === t || (insensitive && input.toLowerCase() === t.toLowerCase())) {
return true;
}
} else if (t instanceof RegExp) {
if (insensitive && t.ignoreCase === false) {
t = new RegExp(t.source, t.flags + 'i');
}
return t.test(input);
}
}
return false;
},
/**
* @param {String} input - The input string to convert to a URL-friendly slug.
* @param {String} [sep="-"] - The seperator string between words. Defaults to a "-".
* @param {Boolean} [lower=true] - Toggles whether to convert the output slug to lower-case. Defaults to true.
* @param {Boolean} [camel=false] - Converts camel or VB -case inputs to a friendly slug. Defaults to false.
* @returns {String}
*/
slugify: function (input, sep, lower, camel) {
if (input === null) {
return null;
} else if (typeof input !== 'string') {
throw new Error('Argument for the paramater "input" is not a string or null value type.');
}
if (typeof sep === 'undefined') {
sep = '-';
} else if (sep === null) {
sep = '';
}
let escSep = Strings.escape(sep, Strings.EscapeMethod.REGEXP);
//normalize diacritics and remove un-processable characters.
input = input
.normalize('NFKD')
.replace(/[^\w\s.\-_\\/,:;<>|`~!@#$%^&*()[\]]/g, '');
//handle camel-case inputs
if (camel) {
input = input.split('').reduce((pv, cv, index, arr) => {
if (cv.match(/[A-Z]/) && pv.match(/[^A-Z]$/)) {
return pv + sep + cv;
} else if (cv.match(/[A-Z]/) && pv.match(/[A-Z]/) && arr.length > index + 1 && arr[index + 1].match(/[a-z-]/)) {
//current is upper, last was upper, but next is lower (possible tail of uppercase chain)
return pv + sep + cv;
}
return pv + cv;
}, '');
}
input = input
.replace(/[\s.\-_\\/,:;<>|`~!@#$%^&*()[\]]+/g, sep) //replace allowed punctuation
.replace(new RegExp(`^${escSep}*|${escSep}*$`, 'g'), '') //trim ends
.replace(new RegExp(escSep + '+', 'g'), sep); //collapse dashes
//make the output lowercase if specified.
if (typeof lower === 'undefined' || lower) {
input = input.toLowerCase();
}
return input;
},
/**
* Converts an input string to a consistent camel-Case name.
* @param {String} input - The name to be standardized.
* @param {Boolean} [pascal=false] - Optional flag that when `true` will always capitalize the first letter.
* @returns {String}
*/
camelify: function (input, pascal = false) {
if (input) {
const alwaysUpper = /^(GU|UU)?ID$/i;
if (alwaysUpper.test(input)) {
return input.toUpperCase();
}
//normalize diacritics and remove un-processable characters and split into words.
let words = input
.normalize('NFKD')
.replace(/[^\w\s.\-_\\/,:;<>|`~!@#$%^&*()[]]/g, '')
.split(/(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z0-9])|[^A-Za-z0-9]/g);
input = words.reduce((pv, cv, i) => {
if (cv.length) {
let uppered = cv.toUpperCase();
let lowered = cv.toLowerCase();
//if a single word name and uppercase, always just return lowercase, except when a reserved
//keyword or only two characters.
if ((uppered.length <= 2 && uppered === cv) || alwaysUpper.test(cv)) {
return pv + uppered;
}
if (!pv) {
return pv + lowered;
} else {
return pv + uppered.substring(0, 1) + lowered.substring(1);
}
}
return pv + cv;
}, '');
if (pascal) {
return input[0].toUpperCase() + input.substring(1);
}
}
return input;
},
/**
* Truncates a given string up to the max. length, and adds an ellipsis if necessary.
* @param {String} input - The string to (potentially) truncate.
* @param {Number} max - The max. length of the input string allowed before it is truncated.
* @returns {String}
*/
truncate: function (input, max) {
return (input.length < max) ? input : input.substring(0, max).replace(/.{3}$/gi, '...');
},
/**
* Truncates a given string from the tail-end (reverse truncate) up to the max. length, and adds an ellipsis if
* necessary.
* @param {String} input - The string to (potentially) truncate.
* @param {Number} max - The max. length of the input string allowed before it is truncated.
* @returns {String}
*/
tail: function (input, max) {
return (input.length < max) ? input : input.substring(input.length - max).replace(/^.{3}/gi, '...');
},
/**
* Indents all or specific lines of text in a string.
* @param {String} input - The string to indent.
* @param {Number} [start] - The line index to start indenting.
* @param {Number} [end] - The line index to stop indenting after.
* @param {String} [indent=" "] - The indentation to use on each matched line.
* @returns {String}
*/
indent: function (input, start, end, indent = ' ') {
if (typeof input === 'string') {
let hasStart = !(typeof start === 'undefined' || start === null);
let hasEnd = !(typeof end === 'undefined' || end === null);
let counter = 0;
return input.replace(/^/gm, (_match, _index, _str) => {
let output = '';
if (hasStart === false || (hasStart && counter >= start)) {
if (hasEnd === false || (hasEnd && counter <= end)) {
output = indent;
}
}
counter++;
return output;
});
}
return input;
},
/**
* Converts a string to title case, where each word and segment has the first character capitalized.
* @param {String} input - The string to convert to title-case.
* @returns {String}
* @example
* ```js
* Strings.title('this IS_a.bunch-OF words.');
* //"This Is_A.Bunch-Of Words"
* ```
*/
title: function (input) {
return input.toLowerCase().replace(/[^\s_'-]+/g,
(word) => {
return word.replace(/^./, (firstLetter) => firstLetter.toUpperCase());
});
},
/**
* Removes markdown or HTML formatting from the specified text - attempting to keep the displayed text content.
* This also converts some escaped entities back to their original characters.
* @param {String} input - The text to strip markdown formatting from.
* @param {Strings.StripFormat} format - The format to strip from the text.
* @returns {String}
*/
strip: function (input, format) {
if (input && typeof input === 'string') {
if (!format || format === Strings.StripFormat.MARKDOWN) {
input = input
.replace(/#{1,}\s*(.+)$/gm, '$1')
.replace(/~~(.+)~~$/gm, '(redacted)')
.replace(/_{1,}|\*|~|!?(?:\[([^\]]*)\]\([^)]*\))/gm, '$1')
.replace(/\n{2,}/gm, '\n\n') //collapse multiple newlines
.trim();
}
if (format === Strings.StripFormat.HTML) {
input = input
.replace(/<a.*href=['"]![^>]*>(?:.|\r|\n)*?<\/a>/gm, '') //strip macro HTML links
.replace(/<li([^>]*)>/gi, '- ') //convert list items to dashes
.replace(/<[^>]*>?/gm, '') //strip all html
.replace(/^ +| +$/gm, '') //remove leading/trailing spaces
.replace(/\n{2,}/gm, '\n\n') //collapse multiple newlines
.trim();
}
input = input
.replace(/Œ/g, 'Œ')
.replace(/œ/g, 'œ')
.replace(/Š/g, 'Š')
.replace(/š/g, 'š')
.replace(/Ÿ/g, 'Ÿ')
.replace(/ƒ/g, 'ƒ')
.replace(/ˆ/g, 'ˆ')
.replace(/˜/g, '˜')
.replace(/ /g, ' ')
.replace(/ /g, ' ')
.replace(/ /g, ' ')
.replace(/‌/g, '')
.replace(/‍/g, '')
.replace(/–/g, '–')
.replace(/—/g, '—')
.replace(/‘/g, '‘')
.replace(/’/g, '’')
.replace(/‚/g, '‚')
.replace(/“/g, '“')
.replace(/”/g, '”')
.replace(/„/g, '„')
.replace(/†/g, '†')
.replace(/‡/g, '‡')
.replace(/•/g, '•')
.replace(/…/g, '…')
.replace(/‰/g, '‰')
.replace(/′/g, '′')
.replace(/″/g, '″')
.replace(/‹/g, '‹')
.replace(/›/g, '›')
.replace(/‾/g, '‾')
.replace(/€/g, '€')
.replace(/™/g, '™')
.replace(/←/g, '←')
.replace(/↑/g, '↑')
.replace(/→/g, '→')
.replace(/↓/g, '↓')
.replace(/↔/g, '↔')
.replace(/↵/g, '↵')
.replace(/⌈/g, '⌈')
.replace(/⌉/g, '⌉')
.replace(/⌊/g, '⌊')
.replace(/⌋/g, '⌋')
.replace(/◊/g, '◊')
.replace(/♠/g, '♠')
.replace(/♣/g, '♣')
.replace(/♥/g, '♥')
.replace(/♦/g, '♦')
.replace(/∀/g, '∀')
.replace(/∂/g, '∂')
.replace(/∃/g, '∃')
.replace(/∅/g, '∅')
.replace(/∇/g, '∇')
.replace(/∈/g, '∈')
.replace(/∉/g, '∉')
.replace(/∋/g, '∋')
.replace(/∏/g, '∏')
.replace(/∑/g, '∑')
.replace(/−/g, '−')
.replace(/∗/g, '∗')
.replace(/√/g, '√')
.replace(/∝/g, '∝')
.replace(/∞/g, '∞')
.replace(/∠/g, '∠')
.replace(/∧/g, '∧')
.replace(/∨/g, '∨')
.replace(/∩/g, '∩')
.replace(/∪/g, '∪')
.replace(/∫/g, '∫')
.replace(/∴/g, '∴')
.replace(/∼/g, '∼')
.replace(/≅/g, '≅')
.replace(/≈/g, '≈')
.replace(/≠/g, '≠')
.replace(/≡/g, '≡')
.replace(/≤/g, '≤')
.replace(/≥/g, '≥')
.replace(/⊂/g, '⊂')
.replace(/⊃/g, '⊃')
.replace(/⊄/g, '⊄')
.replace(/⊆/g, '⊆')
.replace(/⊇/g, '⊇')
.replace(/⊕/g, '⊕')
.replace(/⊗/g, '⊗')
.replace(/⊥/g, '⊥')
.replace(/⋅/g, '⋅')
.replace(/ /g, ' ')
.replace(/¡/g, '¡')
.replace(/¢/g, '¢')
.replace(/£/g, '£')
.replace(/¤/g, '¤')
.replace(/¥/g, '¥')
.replace(/¦/g, '¦')
.replace(/§/g, '§')
.replace(/¨/g, '¨')
.replace(/©/g, '©')
.replace(/ª/g, 'ª')
.replace(/«/g, '«')
.replace(/¬/g, '¬')
.replace(/­/g, '')
.replace(/®/g, '®')
.replace(/¯/g, '¯')
.replace(/°/g, '°')
.replace(/±/g, '±')
.replace(/²/g, '²')
.replace(/³/g, '³')
.replace(/´/g, '´')
.replace(/µ/g, 'µ')
.replace(/¶/g, '¶')
.replace(/¸/g, '¸')
.replace(/¹/g, '¹')
.replace(/º/g, 'º')
.replace(/»/g, '»')
.replace(/¼/g, '¼')
.replace(/½/g, '½')
.replace(/¾/g, '¾')
.replace(/¿/g, '¿')
.replace(/×/g, '×')
.replace(/÷/g, '÷');
}
return input;
}
};
/**
* @enum {Number}
* @readonly
*/
Strings.EscapeMethod = {
URI: 0,
REGEXP: 1
};
/**
* @enum {Number}
* @readonly
*/
Strings.StripFormat = {
MARKDOWN: 'markdown',
HTML: 'html'
};
/** @exports Strings */
export default Strings;