UNPKG

3.14 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6const AZ_REGEX = /([A-Z]+)/g;
7const CAMEL_REGEX = /[^A-Za-z0-9]+/g;
8const DASH_REGEX = /^-/;
9const SEP_REGEX = /[-_.]+/g;
10const SPACE_REGEX = / /g;
11const WORD_FIRST_REGEX = /(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g;
12
13module.exports = class StringHelper {
14
15 static generateLabel (name) {
16 return this.toFirstUpperCase(this.camelToWords(name).toLowerCase());
17 }
18
19 static toFirstUpperCase (text) {
20 text = typeof text === 'string' ? text : String(text);
21 return text.charAt(0).toUpperCase() + text.slice(1);
22 }
23
24 static toFirstLowerCase (text) {
25 text = typeof text === 'string' ? text : String(text);
26 return text.charAt(0).toLowerCase() + text.slice(1);
27 }
28
29 static toWordFirstUpperCase (text) {
30 text = typeof text === 'string' ? text : String(text);
31 return text.replace(WORD_FIRST_REGEX, $1 => $1.toUpperCase());
32 }
33
34 static camelize (text) {
35 text = typeof text === 'string' ? text : String(text);
36 return this.toWordFirstUpperCase(text.replace(CAMEL_REGEX, ' ')).replace(SPACE_REGEX, '');
37 }
38
39 static camelToWords (text) {
40 text = typeof text === 'string' ? text : String(text);
41 return text.replace(SEP_REGEX, ' ').replace(AZ_REGEX, ' $1').trim();
42 }
43
44 static camelToId (text) {
45 text = typeof text === 'string' ? text : String(text);
46 return text.replace(AZ_REGEX, '-$1').replace(DASH_REGEX, '').toLowerCase();
47 }
48
49 static idToCamel (text) {
50 text = typeof text === 'string' ? text : String(text);
51 return this.toWordFirstUpperCase(text.split('-').join(' ')).replace(SPACE_REGEX, '');
52 }
53
54 static split (text, separator = ',') {
55 if (Array.isArray(text)) {
56 return text;
57 }
58 if (typeof text !== 'string') {
59 return [];
60 }
61 return text.split(separator).map(item => item.trim()).filter(item => item.length);
62 }
63
64 static splitFirst (text, separator = '.') {
65 const index = text.indexOf(separator);
66 return index === -1 ? [text] : [text.substring(0, index), text.substring(index + 1)];
67 }
68
69 static splitLast (text, separator = '.') {
70 const index = text.lastIndexOf(separator);
71 return index === -1 ? [text] : [text.substring(0, index), text.substring(index + 1)];
72 }
73
74 static parseObject (text) {
75 if (typeof text !== 'string') {
76 return {};
77 }
78 const result = {};
79 for (const item of text.split(',')) {
80 const [key, value] = item.split(':');
81 if (key !== '' && value !== undefined) {
82 result[key.trim()] = value.trim();
83 }
84 }
85 return result;
86 }
87
88 static trimEnd (text, end) {
89 const index = typeof end === 'string' ? text.lastIndexOf(end) : -1;
90 text = typeof text === 'string' ? text : String(text);
91 return index === -1 ? text : text.substring(0, index);
92 }
93};
\No newline at end of file