-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring-utils.ts
348 lines (295 loc) · 10.5 KB
/
string-utils.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
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
import { StringMap } from "../types";
import { join } from "./array-utils";
import * as StringCheckers from "./string-checkers";
const accentedLowerCharacters = "ąàáäâãåæăćčĉďęèéëêĝĥìíïîĵłľńňòóöőôõðøśșşšŝťțţŭùúüűûñÿýçżźž";
const normalLowerCharacters = "aaaaaaaaacccdeeeeeghiiiijllnnoooooooossssstttuuuuuunyyczzz";
const accentedCharacters = accentedLowerCharacters + accentedLowerCharacters.toUpperCase();
const normalCharacters = normalLowerCharacters + normalLowerCharacters.toUpperCase();
/* TODO:
static underscore(word) {
}
static humanize(word) {
}
static dasherize(word) {
}
//dashCase = a-b-c-d-e
//dotCase a.c.d.v.s.d
//pascalCase = FooBarBaz
//pathCase = a/b/c/d
//snakeCase = a_b_c_d_
static isUpper(word) {
}
static isLower(word) {
}
*/
export function removeAccentedCharacters(word: string): string {
if (!word || !word.replace) {
return word;
}
return word.replace(/./g, (e: string) => {
const index = accentedCharacters.indexOf(e);
return index >= 0 ? normalCharacters[index] : e;
});
}
/**
* @example
* cutUsing("abcdefghij", 10) => abcdefghij
* cutUsing("abcdefghij", 15) => abcdefghij
* cutUsing("abcdefghij", 9) => abcdefg...
* cutUsing("abcdefghij", 9, "...", false) => abcdefghi...
*/
export function cutUsing(text: string, maxLength: number, suffix = "...", lengthIncludeSuffix = true): string {
if (text.length <= maxLength) {
return text;
}
return text.substr(0, maxLength - (lengthIncludeSuffix ? suffix.length - 1 : 0)) + suffix;
}
export function toUpperSnakeCase(text: string): string {
if (StringCheckers.isCamelCase(text)) {
return text.replace(/([a-z])([A-Z])/g, "$1_$2")
.replace(/([A-Z])([A-Z])/g, "$1_$2")
.toUpperCase();
}
if (StringCheckers.isUpperSnakeCase(text)) {
return text;
}
return text.replace(/(-|_| |\s)+(.)?/g, (i, u, e) => e ? `_${e}` : "")
.replace(/^_/, "")
.toUpperCase();
}
export function toLowerSnakeCase(text: string): string {
if (StringCheckers.isCamelCase(text)) {
return text.replace(/([a-z])([A-Z])/g, "$1_$2")
.replace(/([A-Z])([A-Z])/g, "$1_$2")
.toLowerCase();
}
if (StringCheckers.isLowerSnakeCase(text)) {
return text;
}
return text.replace(/(-|_| |\s)+(.)?/g, (i, u, e) => e ? `_${e}` : "")
.replace(/^_/, "")
.toLowerCase();
}
export function toLowerCamelCase(text: string): string {
if (StringCheckers.isLowerCamelCase(text)) {
return text;
}
return text.trim()
.replace(/([a-z])([A-Z])([A-Z])/g, "$1$2_$3")
.replace(/([a-z])([A-Z])/g, "$1_$2")
.toLowerCase()
.replace(/(-|_| |\s)+(.)?/g, (math, sep, c) => c ? c.toUpperCase() : "")
.replace(/^./, (e) => e.toLowerCase());
}
export function toUpperCamelCase(text: string): string {
if (StringCheckers.isUpperCamelCase(text)) {
return text;
}
return toCapital(toLowerCamelCase(text));
}
/**
* @example
* capitalize("gabo") => Gabo
* capitalize("GABO") => Gabo
* capitalize("gABO") => Gabo
*/
export function capitalize(text: string): string {
return text.toLowerCase().replace(/^./, (char) => char.toUpperCase());
}
/**
* @deprecated use {@link capitalize} instead
*/
export function toCapital(text: string): string {
return text.replace(/^./, (e) => e.toUpperCase());
}
export function getLastPart(text: string, divider = " "): string {
if (!text || !text.split) {
return text;
}
const splitText = text.split(divider);
return splitText[splitText.length - 1];
}
/**
* @deprecated use {@link occurrences} instead
*/
export function count(text: string, key: string): number {
// eslint-disable-next-line
return (text.match(new RegExp(key, "g")) || []).length;
}
/**
* @param text - text need to be repeat
* @param numberOfRepetitions - number of iterations
* @deprecated - use {@link String#repeat}
*/
export function repeat(text: string, numberOfRepetitions: number): string {
return new Array(numberOfRepetitions + 1).join(text);
}
export function removeAll(text: string, words: string[]): string {
return text.replace(new RegExp(`(${words.join("|")})`, "g"), "");
}
/**
* @example
* template("{{name}} is {{age}} years old", {name: "Gabriel", age: 23}) => Gabriel is 23 years old
*/
export function template(text: string, values: StringMap<unknown>, start = "{{", end = "}}"): string {
const updatedStart = start.replace(/[-[\]()*\s]/g, "\\$&").replace(/\$/g, "\\$");
const updatedEnd = end.replace(/[-[\]()*\s]/g, "\\$&").replace(/\$/g, "\\$");
return text.replace(
new RegExp(`${updatedStart}(.+?)${updatedEnd}`, "g"),
(math, key) => String(values[key]),
);
}
export function removeEmptyLines(content: string): string {
return content.replace(/^\s*$(?:\r\n?|\n)/gm, "");
}
/**
* @example
* between("my name is gabriel and I am 26 years old", "NAME", "gabriel") => "my name is "
* between("my name is gabriel and I am 26 years old", "name", "GABRIEL") => " is gabriel and I am 26 years old"
* between("my name is gabriel and I am 26 years old", "name", "gabriel") => " is "
* between("my name is gabriel and I am 26 years old", "name", "gabriel", true) => "is"
*/
export function between(text: string, key1: string, key2: string, trim = false): string {
const processResult = (result: string): string => trim ? result.trim() : result;
const startPos = text.indexOf(key1);
const endPos = text.indexOf(key2);
if (startPos < 0 && endPos >= 0) {
return processResult(text.substring(0, endPos));
}
if (endPos < 0 && startPos >= 0) {
return processResult(text.substring(startPos + key1.length, text.length));
}
return processResult(text.substring(startPos + key1.length, endPos));
}
/**
* Returns number of occurrences of substring
*
* @version 0.2.40 - much faster then previous regex method using `return (text.match(new RegExp(key, "g")) || []).length;`
* @example
* occurrences("foofoofoo", "bar"); => 0
* occurrences("foofoofoo", "foo"); => 3
* occurrences("foofoofoo", "foofoo"); => 1
* occurrences("foofoofoo", "foofoo", true); => 2
* @param text - text
* @param key - searched substring
* @param overlapping - allows math overlapping
*/
export function occurrences(text: string, key: string, overlapping = false): number {
let index = text.indexOf(key);
let counter = 0;
const step = overlapping ? 1 : key.length;
while (index >= 0) {
counter++;
index = text.indexOf(key, index + step);
}
return counter;
}
export function collapseWhitespace(text: string): string {
return text.replace(/[\s\uFEFF\xA0]{2,}/g, " ");
}
export function swapCase(text: string): string {
return text.replace(/\S/g, (char) => {
const lowerCase = char.toLowerCase();
return lowerCase === char ? char.toUpperCase() : lowerCase;
});
}
/**
* @example
* formatTime("{} is a big {}", ["Gabo", "hero"]) => Gabo is a big hero
* formatTime("<> is a big <>", ["Gabo", "hero"], "<>") => Gabo is a big hero
*/
export function format(text: string, values: string[], placeHolder = "{}"): string {
const result: string[] = [];
let lastIndex;
let actualIndex = 0;
let counter = 0;
while (counter < values.length) {
lastIndex = actualIndex;
actualIndex = text.indexOf(placeHolder, actualIndex);
result.push(text.substring(lastIndex, actualIndex));
result.push(values[counter++]);
actualIndex += placeHolder.length;
}
result.push(text.substring(actualIndex));
return result.join("");
}
export function transformToBasicFormat(text: string): string {
return collapseWhitespace(removeAccentedCharacters(text).toLowerCase()).trim();
}
/**
* @example
* getAsciiArray("abcdefg") ==> [97, 98, 99, 100, 101, 102, 103]
* @param thisArg - argument
*/
export function getAsciiArray(thisArg: string): number[] {
const result = [];
for (const letter of thisArg) {
result[result.length] = letter.charCodeAt(0);
}
return result;
}
export function toBasicForm(text: string): string {
return removeAccentedCharacters(text.toLowerCase());
}
export function contains(text: string, substring: string): boolean {
return !!text && removeAccentedCharacters(text.toLowerCase()).indexOf(substring) >= 0;
}
/**
* @example
* joinSingle("package", ".", "json") => package.json
* joinSingle("package.", ".", "json") => package.json
* joinSingle("package", ".", ".json") => package.json
* joinSingle("package.", ".", ".json") => package.json
*/
export function joinSingle(prefix: string, divider: string, postfix: string): string {
if (postfix.startsWith(divider) && prefix.endsWith(divider)) {
return prefix + postfix.substring(divider.length);
}
if (postfix.startsWith(divider) || prefix.endsWith(divider)) {
return prefix + postfix;
}
return prefix + divider + postfix;
}
/**
* @deprecated use {@link join} instead
* @param data - data to join
* @param delimiter - delimiter
* @param prefix - prefix
* @param postfix - postfix
*/
export function joinString(data: string[], delimiter = " ", prefix = "", postfix = ""): string {
return join(data, delimiter, prefix, postfix);
}
export function getFormattedNumber(num: string, prefix = "+421"): string {
num = num.replace(/[( )/-]/g, "");
if (num.startsWith("+")) {
return num;
}
if (num.startsWith("00")) {
return num.substring(2);
}
if (num.startsWith("09") || num.startsWith("02")) {
return prefix + num.substring(1);
}
return num;
}
function fuzzy_match_simple(pattern: string, str: string): boolean {
let patternIdx = 0;
let strIdx = 0;
const patternLength = pattern.length;
const strLength = str.length;
while (patternIdx !== patternLength && strIdx !== strLength) {
const patternChar = pattern.charAt(patternIdx)
.toLowerCase();
const strChar = str.charAt(strIdx)
.toLowerCase();
if (patternChar === strChar) {
++patternIdx;
}
++strIdx;
}
return patternLength !== 0 && strLength !== 0 && patternIdx === patternLength;
}
export function replaceForAll(content: string, values: string[], placeHolder: string): string[] {
return values.map((value) => content.replace(placeHolder, value));
}