npm-lodash

Description
Comprehensive JavaScript utility library with 300+ methods for arrays, objects, strings, functions, and more.
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/npm-lodash@4.5.0

string-methods.md docs/

1
# String Methods
2
3
String manipulation utilities for case conversion, formatting, templating, and parsing. These methods provide comprehensive text processing capabilities for JavaScript applications.
4
5
## Capabilities
6
7
### Case Conversion
8
9
#### camelCase & Related Cases
10
Converts strings to various naming conventions.
11
12
```javascript { .api }
13
/**
14
* Converts string to camel case
15
* @param string - The string to convert
16
* @returns Returns the camel cased string
17
*/
18
function camelCase(string);
19
20
/**
21
* Converts string to kebab case
22
* @param string - The string to convert
23
* @returns Returns the kebab cased string
24
*/
25
function kebabCase(string);
26
27
/**
28
* Converts string to snake case
29
* @param string - The string to convert
30
* @returns Returns the snake cased string
31
*/
32
function snakeCase(string);
33
34
/**
35
* Converts string to start case
36
* @param string - The string to convert
37
* @returns Returns the start cased string
38
*/
39
function startCase(string);
40
41
/**
42
* Converts string to lower case
43
* @param string - The string to convert
44
* @returns Returns the lower case string
45
*/
46
function lowerCase(string);
47
48
/**
49
* Converts string to upper case
50
* @param string - The string to convert
51
* @returns Returns the upper case string
52
*/
53
function upperCase(string);
54
```
55
56
#### Capitalization
57
Capitalizes or changes case of first characters.
58
59
```javascript { .api }
60
/**
61
* Converts the first character of string to upper case and the remaining to lower case
62
* @param string - The string to capitalize
63
* @returns Returns the capitalized string
64
*/
65
function capitalize(string);
66
67
/**
68
* Converts the first character of string to lower case
69
* @param string - The string to convert
70
* @returns Returns the converted string
71
*/
72
function lowerFirst(string);
73
74
/**
75
* Converts the first character of string to upper case
76
* @param string - The string to convert
77
* @returns Returns the converted string
78
*/
79
function upperFirst(string);
80
```
81
82
#### Native Case Methods
83
Direct access to native string case methods.
84
85
```javascript { .api }
86
/**
87
* Converts string, as a whole, to lower case just like String#toLowerCase
88
* @param value - The string to convert
89
* @returns Returns the lower cased string
90
*/
91
function toLower(value);
92
93
/**
94
* Converts string, as a whole, to upper case just like String#toUpperCase
95
* @param value - The string to convert
96
* @returns Returns the upper cased string
97
*/
98
function toUpper(value);
99
```
100
101
### String Padding & Trimming
102
103
#### Padding
104
Pads strings to a specified length.
105
106
```javascript { .api }
107
/**
108
* Pads string on the left and right sides if it's shorter than length
109
* @param string - The string to pad
110
* @param length - The padding length
111
* @param chars - The string used as padding
112
* @returns Returns the padded string
113
*/
114
function pad(string, length = 0, chars = ' ');
115
116
/**
117
* Pads string on the right side if it's shorter than length
118
* @param string - The string to pad
119
* @param length - The padding length
120
* @param chars - The string used as padding
121
* @returns Returns the padded string
122
*/
123
function padEnd(string, length = 0, chars = ' ');
124
125
/**
126
* Pads string on the left side if it's shorter than length
127
* @param string - The string to pad
128
* @param length - The padding length
129
* @param chars - The string used as padding
130
* @returns Returns the padded string
131
*/
132
function padStart(string, length = 0, chars = ' ');
133
```
134
135
#### Trimming
136
Removes whitespace or specified characters from strings.
137
138
```javascript { .api }
139
/**
140
* Removes leading and trailing whitespace or specified characters from string
141
* @param string - The string to trim
142
* @param chars - The characters to trim
143
* @returns Returns the trimmed string
144
*/
145
function trim(string, chars = whitespace);
146
147
/**
148
* Removes trailing whitespace or specified characters from string
149
* @param string - The string to trim
150
* @param chars - The characters to trim
151
* @returns Returns the trimmed string
152
*/
153
function trimEnd(string, chars = whitespace);
154
155
/**
156
* Removes leading whitespace or specified characters from string
157
* @param string - The string to trim
158
* @param chars - The characters to trim
159
* @returns Returns the trimmed string
160
*/
161
function trimStart(string, chars = whitespace);
162
```
163
164
### String Testing
165
166
#### startsWith & endsWith
167
Tests string prefixes and suffixes.
168
169
```javascript { .api }
170
/**
171
* Checks if string starts with target string
172
* @param string - The string to inspect
173
* @param target - The string to search for
174
* @param position - The position to search from
175
* @returns Returns true if string starts with target, else false
176
*/
177
function startsWith(string, target, position = 0);
178
179
/**
180
* Checks if string ends with target string
181
* @param string - The string to inspect
182
* @param target - The string to search for
183
* @param position - The position to search up to
184
* @returns Returns true if string ends with target, else false
185
*/
186
function endsWith(string, target, position = string.length);
187
```
188
189
### String Manipulation
190
191
#### repeat
192
Repeats the given string n times.
193
194
```javascript { .api }
195
/**
196
* Repeats the given string n times
197
* @param string - The string to repeat
198
* @param n - The number of times to repeat the string
199
* @returns Returns the repeated string
200
*/
201
function repeat(string, n = 1);
202
```
203
204
#### replace
205
Replaces matches for pattern in string with replacement.
206
207
```javascript { .api }
208
/**
209
* Replaces matches for pattern in string with replacement
210
* @param string - The string to modify
211
* @param pattern - The pattern to replace
212
* @param replacement - The match replacement
213
* @returns Returns the modified string
214
*/
215
function replace(string, pattern, replacement);
216
```
217
218
#### split
219
Splits string by separator until limit is reached.
220
221
```javascript { .api }
222
/**
223
* Splits string by separator until limit is reached
224
* @param string - The string to split
225
* @param separator - The separator pattern to split by
226
* @param limit - The length to truncate results to
227
* @returns Returns the string segments
228
*/
229
function split(string, separator, limit);
230
```
231
232
#### truncate
233
Truncates string if it's longer than the given maximum string length.
234
235
```javascript { .api }
236
/**
237
* Truncates string if it's longer than the given maximum string length
238
* @param string - The string to truncate
239
* @param options - The options object
240
* @returns Returns the truncated string
241
*/
242
function truncate(string, options);
243
244
// Options interface
245
interface TruncateOptions {
246
length?: number; // Maximum string length (default: 30)
247
omission?: string; // String to indicate text is omitted (default: '...')
248
separator?: RegExp | string; // Separator pattern to truncate to
249
}
250
```
251
252
### String Processing
253
254
#### deburr
255
Deburrs string by converting Latin-1 Supplement and Latin Extended-A letters to basic Latin letters.
256
257
```javascript { .api }
258
/**
259
* Deburrs string by converting Latin-1 Supplement and Latin Extended-A letters to basic Latin letters and removing combining diacritical marks
260
* @param string - The string to deburr
261
* @returns Returns the deburred string
262
*/
263
function deburr(string);
264
```
265
266
#### words
267
Splits string into an array of its words.
268
269
```javascript { .api }
270
/**
271
* Splits string into an array of its words
272
* @param string - The string to inspect
273
* @param pattern - The pattern to match words
274
* @returns Returns the words of string
275
*/
276
function words(string, pattern);
277
```
278
279
### HTML & RegExp Escaping
280
281
#### escape & unescape
282
Converts characters to HTML entities and vice versa.
283
284
```javascript { .api }
285
/**
286
* Converts the characters "&", "<", ">", '"', and "'" in string to their corresponding HTML entities
287
* @param string - The string to escape
288
* @returns Returns the escaped string
289
*/
290
function escape(string);
291
292
/**
293
* The inverse of escape; converts HTML entities "&amp;", "&lt;", "&gt;", "&quot;", and "&#39;" to their corresponding characters
294
* @param string - The string to unescape
295
* @returns Returns the unescaped string
296
*/
297
function unescape(string);
298
```
299
300
#### escapeRegExp
301
Escapes RegExp special characters.
302
303
```javascript { .api }
304
/**
305
* Escapes the RegExp special characters "^", "$", "\", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", and "|" in string
306
* @param string - The string to escape
307
* @returns Returns the escaped string
308
*/
309
function escapeRegExp(string);
310
```
311
312
### Number Parsing
313
314
#### parseInt
315
Converts string to an integer of the specified radix.
316
317
```javascript { .api }
318
/**
319
* Converts string to an integer of the specified radix
320
* @param string - The string to convert
321
* @param radix - The radix to interpret the value by
322
* @returns Returns the converted integer
323
*/
324
function parseInt(string, radix = 10);
325
```
326
327
### Template Processing
328
329
#### template
330
Creates a compiled template function that can interpolate data properties.
331
332
```javascript { .api }
333
/**
334
* Creates a compiled template function that can interpolate data properties in "interpolate" delimiters, HTML-escape interpolated data properties in "escape" delimiters, and execute JavaScript in "evaluate" delimiters
335
* @param string - The template string
336
* @param options - The options object
337
* @returns Returns the compiled template function
338
*/
339
function template(string, options);
340
341
// Template options interface
342
interface TemplateOptions {
343
escape?: RegExp; // HTML "escape" delimiter
344
evaluate?: RegExp; // JavaScript "evaluate" delimiter
345
interpolate?: RegExp; // Data property "interpolate" delimiter
346
sourceURL?: string; // Source URL of the template
347
variable?: string; // Data object variable name
348
imports?: object; // Object of template imports
349
}
350
351
// Compiled template function
352
interface CompiledTemplate {
353
(data?: object): string;
354
source: string;
355
}
356
```
357
358
## Template Syntax
359
360
Lodash templates support three types of delimiters:
361
362
```javascript { .api }
363
// Interpolation: <%= variable %>
364
const template1 = template('Hello <%= name %>!');
365
template1({ name: 'John' }); // → 'Hello John!'
366
367
// HTML Escaping: <%- variable %>
368
const template2 = template('User: <%- user %>');
369
template2({ user: '<script>' }); // → 'User: &lt;script&gt;'
370
371
// JavaScript Evaluation: <% code %>
372
const template3 = template('<% if (user) { %>Hello <%= user %>!<% } %>');
373
template3({ user: 'John' }); // → 'Hello John!'
374
```
375
376
## Usage Examples
377
378
```javascript
379
import {
380
camelCase, kebabCase, snakeCase, capitalize,
381
pad, trim, startsWith, endsWith, repeat,
382
replace, split, truncate, escape, template
383
} from "lodash";
384
385
// Case conversion
386
const title = 'hello world';
387
console.log(camelCase(title)); // 'helloWorld'
388
console.log(kebabCase(title)); // 'hello-world'
389
console.log(snakeCase(title)); // 'hello_world'
390
console.log(capitalize(title)); // 'Hello world'
391
392
// String formatting
393
const text = ' hello world ';
394
console.log(trim(text)); // 'hello world'
395
console.log(pad('42', 5, '0')); // '00420'
396
397
// String testing
398
const filename = 'document.pdf';
399
console.log(startsWith(filename, 'doc')); // true
400
console.log(endsWith(filename, '.pdf')); // true
401
402
// String manipulation
403
console.log(repeat('*', 5)); // '*****'
404
console.log(replace('hello world', 'world', 'universe')); // 'hello universe'
405
406
// Text processing
407
const sentence = 'The quick brown fox jumps over the lazy dog';
408
console.log(split(sentence, ' ', 3)); // ['The', 'quick', 'brown']
409
console.log(truncate(sentence, { length: 20 })); // 'The quick brown fox...'
410
411
// HTML safety
412
const userInput = '<script>alert("xss")</script>';
413
console.log(escape(userInput)); // '&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;'
414
415
// Template processing
416
const greetingTemplate = template('Hello <%= name %>! You have <%= count %> messages.');
417
const greeting = greetingTemplate({ name: 'Alice', count: 3 });
418
console.log(greeting); // 'Hello Alice! You have 3 messages.'
419
420
// Advanced templates
421
const listTemplate = template(`
422
<ul>
423
<% items.forEach(function(item) { %>
424
<li><%- item.name %> - $<%= item.price %></li>
425
<% }); %>
426
</ul>
427
`);
428
429
const items = [
430
{ name: 'Coffee & Cake', price: 4.99 },
431
{ name: 'Tea', price: 2.99 }
432
];
433
434
const html = listTemplate({ items });
435
// Generates properly escaped HTML list
436
437
// Complex case conversions
438
const apiEndpoint = 'GET_USER_PROFILE';
439
console.log(camelCase(apiEndpoint)); // 'getUserProfile'
440
console.log(kebabCase(apiEndpoint)); // 'get-user-profile'
441
442
// String cleaning and normalization
443
const messyString = ' Café & Restaurant ';
444
const cleaned = trim(deburr(messyString)); // 'Cafe & Restaurant'
445
446
// Pattern-based word splitting
447
const text2 = 'camelCaseString';
448
console.log(words(text2)); // ['camel', 'Case', 'String']
449
450
// Safe string building
451
const buildUrl = (base, ...segments) => {
452
const cleanBase = trimEnd(base, '/');
453
const cleanSegments = segments.map(s => trim(s, '/'));
454
return [cleanBase, ...cleanSegments].join('/');
455
};
456
457
console.log(buildUrl('https://api.example.com/', '/users/', '/123/'));
458
// 'https://api.example.com/users/123'
459
```