1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const AZ_REGEX = /([A-Z]+)/g;
|
7 | const CAMEL_REGEX = /[^A-Za-z0-9]+/g;
|
8 | const DASH_REGEX = /^-/;
|
9 | const SEP_REGEX = /[-_.]+/g;
|
10 | const SPACE_REGEX = / /g;
|
11 | const WORD_FIRST_REGEX = /(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g;
|
12 |
|
13 | module.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 parseObject (text) {
|
65 | if (typeof text !== 'string') {
|
66 | return {};
|
67 | }
|
68 | const result = {};
|
69 | for (const item of text.split(',')) {
|
70 | const [key, value] = item.split(':');
|
71 | if (key !== '' && value !== undefined) {
|
72 | result[key.trim()] = value.trim();
|
73 | }
|
74 | }
|
75 | return result;
|
76 | }
|
77 |
|
78 | static trimEnd (text, end) {
|
79 | const index = typeof end === 'string' ? text.lastIndexOf(end) : -1;
|
80 | text = typeof text === 'string' ? text : String(text);
|
81 | return index === -1 ? text : text.substring(0, index);
|
82 | }
|
83 | }; |
\ | No newline at end of file |