-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring-utils.ts
More file actions
334 lines (297 loc) · 12.2 KB
/
string-utils.ts
File metadata and controls
334 lines (297 loc) · 12.2 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
/**
* @class StringUtils
* @description A utility class for performing common string manipulations
* in a chainable, fluent manner. Designed for easy use without needing
* the 'new' keyword, and for straightforward retrieval of the final string.
*/
class StringUtils {
/**
* @private
* @description The private instance variable to hold the current string value.
*/
private currentString: string;
/**
* @private constructor
* @description The constructor is private. This enforces that new instances
* are always created using the static `StringUtils.of()` factory method.
* This makes the API feel more like built-in JavaScript functions.
* @param {string} initialValue The string to start chaining operations on.
*/
private constructor(initialValue: string) {
this.currentString = String(initialValue);
}
/**
* @static
* @method of
* @description The primary way to create a new StringUtils instance and start a chain.
* This method acts as a "factory," returning a new StringUtils object that's ready
* for you to apply string operations to.
* @param {string} initialValue The string you want to begin manipulating.
* @returns {StringUtils} A new StringUtils instance, enabling method chaining.
* @example
* // Start a new string utility chain
* StringUtils.of(" hello world ")
*/
static of(initialValue: string): StringUtils {
return new StringUtils(initialValue);
}
/**
* @method capitalize
* @description Capitalizes the very first letter of the string.
* For example, "hello" becomes "Hello".
* @returns {StringUtils} The current StringUtils instance for continued chaining.
*/
capitalize(): this {
if (this.currentString.length === 0) {
return this;
}
this.currentString = this.currentString.charAt(0).toUpperCase() + this.currentString.slice(1);
return this;
}
/**
* @method capitalizeWords
* @description Capitalizes the first letter of each word in the string.
* Words are typically separated by spaces.
* For example, "hello world" becomes "Hello World".
* @returns {StringUtils} The current StringUtils instance for continued chaining.
*/
capitalizeWords(): this {
this.currentString = this.currentString
.split(" ")
.map((word) =>
word.length === 0 ? "" : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(),
)
.join(" ");
return this;
}
/**
* @method toUpperCase
* @description Converts the entire string to uppercase letters.
* For example, "Hello" becomes "HELLO".
* @returns {StringUtils} The current StringUtils instance for continued chaining.
*/
toUpperCase(): this {
this.currentString = this.currentString.toUpperCase();
return this;
}
/**
* @method toLowerCase
* @description Converts the entire string to lowercase letters.
* For example, "HELLO" becomes "hello".
* @returns {StringUtils} The current StringUtils instance for continued chaining.
*/
toLowerCase(): this {
this.currentString = this.currentString.toLowerCase();
return this;
}
/**
* @method trim
* @description Removes whitespace characters (like spaces, tabs, newlines)
* from both the beginning and the end of the string.
* @returns {StringUtils} The current StringUtils instance for continued chaining.
* @remark
* The built-in `String.prototype.trim()` method is highly optimized and
* robust. It handles all whitespace characters defined by the Unicode
* White_Space property, which includes regular spaces, tabs, newlines,
* and various non-breaking space characters.
* For most web development scenarios, the native `trim()`
* is the recommended and most commonly used approach over regex.
*/
trim(): this {
this.currentString = this.currentString.trim();
return this;
}
/**
* @method replace
* @description **Overload 1:** Replaces the first occurrence of `searchValue` with `replaceValue`.
* @param {string | RegExp} searchValue The value to search for (a string or a regular expression).
* @param {string} replaceValue The string to replace with.
* @returns {StringUtils} The current StringUtils instance for continued chaining.
*/
replace(searchValue: string | RegExp, replaceValue: string): this;
/**
* @method replace
* @description **Overload 2:** Replaces occurrences of `searchValue` using a replacer function.
* @param {string | RegExp} searchValue The value to search for (a string or a regular expression).
* @param {(substring: string, ...args: any[]) => string} replacer
* A function that returns the replacement string. Its arguments typically include the matched substring,
* captured groups, and the offset of the match.
* @returns {StringUtils} The current StringUtils instance for continued chaining.
*/
replace(
searchValue: string | RegExp,
replacer: (substring: string, ...args: any[]) => string,
): this;
/**
* @method replace
* @description **Implementation:** Handles both string and function replacements.
* @param {string | RegExp} searchValue
* @param {string | ((substring: string, ...args: any[]) => string)} replaceValue
* @returns {StringUtils}
*/
replace(
searchValue: string | RegExp,
replaceValue: string | ((substring: string, ...args: any[]) => string),
): this {
this.currentString = this.currentString.replace(searchValue, replaceValue as any);
return this;
}
/**
* @method prepend
* @description Adds a string to the beginning of the current string value.
* @param {string} prefix The string to add before the current string.
* @returns {StringUtils} The current StringUtils instance for continued chaining.
*/
prepend(prefix: string): this {
this.currentString = prefix + this.currentString;
return this;
}
/**
* @method append
* @description Adds a string to the end of the current string value.
* @param {string} suffix The string to add after the current string.
* @returns {StringUtils} The current StringUtils instance for continued chaining.
*/
append(suffix: string): this {
this.currentString = this.currentString + suffix;
return this;
}
/**
* @method isEmpty
* @description Checks if the current string is effectively empty, meaning it has a length of 0
* after trimming any whitespace.
* This method does not modify the string being chained.
* @returns {boolean} True if the string is empty or contains only whitespace, false otherwise.
* @example
* StringUtils.of("").isEmpty(); // true
* StringUtils.of(" ").isEmpty(); // true
* StringUtils.of(" hello ").isEmpty(); // false
*/
isEmpty(): boolean {
return this.currentString.trim().length === 0;
}
/**
* @method isLessThan
* @description Checks if the length of the current string is less than a specified number.
* This method does not modify the string.
* @param {number} length The number to compare against.
* @returns {boolean} True if the string's length is less than the given length, false otherwise.
* @example
* StringUtils.of("abc").isLessThan(5); // true
* StringUtils.of("abcdef").isLessThan(5); // false
*/
isLessThan(length: number): boolean {
return this.currentString.length < length;
}
/**
* @method isMoreThan
* @description Checks if the length of the current string is more than a specified number.
* This method does not modify the string.
* @param {number} length The number to compare against.
* @returns {boolean} True if the string's length is more than the given length, false otherwise.
* @example
* StringUtils.of("abcdef").isMoreThan(5); // true
* StringUtils.of("abc").isMoreThan(5); // false
*/
isMoreThan(length: number): boolean {
return this.currentString.length > length;
}
/**
* @method isEqual
* @description Checks if the current string is exactly equal to another string.
* This performs a case-sensitive comparison.
* This method does not modify the string.
* @param {string} compareString The string to compare against.
* @returns {boolean} True if the strings are equal, false otherwise.
* @example
* StringUtils.of("hello").isEqual("hello"); // true
* StringUtils.of("hello").isEqual("Hello"); // false
*/
isEqual(compareString: string): boolean {
return this.currentString === compareString;
}
/**
* @property {string} value
* @description A getter property to retrieve the final string value after all chained operations.
* Using it like a property (`.value`) makes the end of the chain very clear and readable.
* @returns {string} The current string value stored in this StringUtils instance.
*/
get value(): string {
return this.currentString;
}
/**
* @method valueOf
* @description Returns the final string value. This is a JavaScript built-in method
* that allows the StringUtils object to be treated as its primitive string value
* in certain contexts (e.g., when coercing to string).
* @returns {string} The current string value.
*/
valueOf(): string {
return this.currentString;
}
/**
* @method toString
* @description Returns the final string value. This is another JavaScript built-in method
* often called when an object needs to be represented as a string.
* It's an alias for `valueOf()` in this class.
* @returns {string} The current string value.
*/
toString(): string {
return this.currentString;
}
}
// --- Example Usage ---
console.log("--- StringUtils Examples ---");
// Example 1: Basic chaining
const processedName = StringUtils.of(" ALICE SMITH ")
.trim() // "ALICE SMITH"
.toLowerCase() // "alice smith"
.capitalize() // "Alice smith"
.replace("smith", "Jones").value; // "Alice Jones" // Get the final string
console.log("Processed Name:", processedName);
// Example 2: Prepending and Appending
const formattedTitle = StringUtils.of("My Article")
.prepend("Read: ") // "Read: My Article"
.append("!") // "Read: My Article!"
.toUpperCase().value; // "READ: MY ARTICLE!"
console.log("Formatted Title:", formattedTitle);
// Example 3: Implicit string conversion (thanks to valueOf/toString)
// Note: While 'valueOf' and 'toString' exist, using '.value' is often more explicit.
const implicitString = StringUtils.of("test").trim();
console.log("Implicit String (might vary by JS engine):", "START_" + implicitString + "_END");
// Example 4: Chaining with replace (RegExp and string replacement)
const cleanText = StringUtils.of(" hello-world-123 ")
.trim()
.replace(/-/g, " ") // Replace all hyphens with spaces
.capitalize().value;
console.log("Clean Text:", cleanText);
// Example 5: Chaining with replace (RegExp and function replacer)
const maskedEmail = StringUtils.of("user@example.com").replace(
/^(.)(.*)(@.*)$/,
(match, firstChar, middle, domain) => {
return firstChar + "*".repeat(middle.length) + domain;
},
).value;
console.log("Masked Email:", maskedEmail);
// Example 6: Capitalize Words
const titleCaseText = StringUtils.of("a short story about a brave knight").capitalizeWords().value;
console.log("Capitalized Words:", titleCaseText);
// --- Validation Examples ---
console.log("\n--- StringUtils Validation Examples ---");
const trulyEmptyString = StringUtils.of("");
console.log("Is empty ('')?", trulyEmptyString.isEmpty());
const whitespaceString = StringUtils.of(" \n\t");
console.log("Is empty (' \\n\\t')?", whitespaceString.isEmpty());
const nonEmptyString = StringUtils.of(" hello ");
console.log("Is empty (' hello ')?", nonEmptyString.isEmpty());
const shortString = StringUtils.of("abc");
console.log("Is 'abc' less than 5?", shortString.isLessThan(5));
console.log("Is 'abc' more than 5?", shortString.isMoreThan(5));
const longString = StringUtils.of("superlongstring");
console.log("Is 'superlongstring' less than 10?", longString.isLessThan(10));
console.log("Is 'superlongstring' more than 10?", longString.isMoreThan(10));
const helloString = StringUtils.of("hello");
console.log("Is 'hello' equal to 'hello'?", helloString.isEqual("hello"));
console.log("Is 'hello' equal to 'Hello'?", helloString.isEqual("Hello"));
// Note: Validation methods like isEmpty, isLessThan, etc., don't return 'this'
// because their purpose is to provide a boolean answer, not to continue the string transformation chain.