UNPKG

13.5 kBMarkdownView Raw
1# string #
2
3String utilities.
4
5
6## camelCase(str):String
7
8Convert string to "camelCase" text.
9
10See: [`pascalCase()`](#pascalCase), [`unCamelCase()`](#unCamelCase)
11
12### Example
13
14```js
15camelCase('lorem-ipsum-dolor'); // "loremIpsumDolor"
16camelCase('lorem ipsum dolor'); // "loremIpsumDolor"
17```
18
19
20
21## contains(str, substring, [fromIndex]):Boolean
22
23Checks if string contains the given substring.
24
25See: [`startsWith()`](#startsWith), [`endsWith()`](#endsWith)
26
27### Example
28
29```js
30contains('lorem', 'or'); // true
31contains('lorem', 'bar'); // false
32```
33
34
35
36## crop(str, maxChars, [append]):String
37
38Truncate string at full words. Alias to `truncate(str, maxChars, append, true);`.
39
40See: [`truncate()`](#truncate)
41
42### Example
43
44```js
45crop('lorem ipsum dolor', 10); // "lorem..."
46crop('lorem ipsum dolor', 10, '+'); // "lorem+"
47```
48
49
50
51## endsWith(str, suffix):Boolean
52
53Checks if string ends with specified suffix.
54
55See: [`startsWith()`](#startsWith), [`contains()`](#contains)
56
57### Example
58
59```js
60endsWith('lorem ipsum', 'lorem'); // false
61endsWith('lorem ipsum', 'ipsum'); // true
62```
63
64
65
66## escapeHtml(str):String
67
68Escapes the following special characters for use in HTML:
69
70* `&` becomes `&`
71* `<` becomes `&lt;`
72* `>` becomes `&gt;`
73* `'` becomes `&#39;`
74* `"` becomes `&quot;`
75
76No other characters are escaped. To HTML-escape other characters as well, use a third-party library like [_he_](http://mths.be/he).
77
78See: [`unescapeHtml()`](#unescapeHtml)
79
80### Example
81
82```js
83escapeHtml('lorem & "ipsum"'); // "lorem &amp;amp; &amp;quot;ipsum&amp;quot;"
84```
85
86
87
88## escapeRegExp(str):String
89
90Escape special chars to be used as literals in RegExp constructors.
91
92### Example
93
94```js
95str = escapeRegExp('[lorem.ipsum]'); // "\\[lorem\\.ipsum\\]"
96reg = new RegExp(str); // /\[lorem\.ipsum\]/
97```
98
99
100
101## escapeUnicode(str[, shouldEscapePrintable]):String
102
103Unicode escape chars.
104
105It will only escape non-printable ASCII chars unless `shouldEscapePrintable` is
106set to `true`.
107
108See: [`unescapeUnicode()`](#unescapeUnicode)
109
110```js
111escapeUnicode('føo bår');
112// > "f\u00f8o b\u00e5r"
113escapeUnicode('føo bår', true);
114// > "\u0066\u00f8\u006f\u0020\u0062\u00e5\u0072"
115```
116
117
118
119## hyphenate(str):String
120
121Replaces spaces with hyphens, split camelCase text, remove non-word chars,
122remove accents and convert to lower case.
123
124See: [`slugify()`](#slugify), [`underscore()`](#underscore),
125[`unhyphenate`](#unhyphenate)
126
127```js
128hyphenate(' %# lorem ipsum ? $ dolor'); // "lorem-ipsum-dolor"
129hyphenate('spéçïãl çhârs'); // "special-chars"
130hyphenate('loremIpsum'); // "lorem-ipsum"
131```
132
133
134
135## insert(str, index, partial):String
136
137Inserts a `partial` before the given `index` in the provided `str`.
138If the index is larger than the length of the string the partial is appended at the end.
139A negative index is treated as `length - index` where `length` is the length or the string.
140
141```js
142insert('this is a sentence', 10, 'sample '); // "this is a sample sentence"
143insert('foo', 100, 'bar'); // "foobar"
144insert('image.png', -4, '-large'); // "image-large.png"
145```
146
147## interpolate(str, replacements[, syntax]):String
148
149String interpolation. Format/replace tokens with object properties.
150
151```js
152var tmpl = 'Hello {{name}}!';
153interpolate(tmpl, {name: 'World'}); // "Hello World!"
154interpolate(tmpl, {name: 'Lorem Ipsum'}); // "Hello Lorem Ipsum!"
155
156tmpl = 'Hello {{name.first}}!';
157interpolate(tmpl, {name: {first: 'Lorem'}}); // "Hello Lorem!"
158```
159
160It uses a mustache-like syntax by default but you can set your own format if
161needed. You can also use Arrays for the replacements (since Arrays are
162objects as well):
163
164```js
165// matches everything inside "${}"
166var syntax = /\$\{([^}]+)\}/g;
167var tmpl = "Hello ${0}!";
168interpolate(tmpl, ['Foo Bar'], syntax); // "Hello Foo Bar!"
169```
170
171
172
173## lowerCase(str):String
174
175"Safer" `String.toLowerCase()`. (Used internally)
176
177### Example
178
179```js
180(null).toLowerCase(); // Error!
181(undefined).toLowerCase(); // Error!
182lowerCase(null); // ""
183lowerCase(undefined); // ""
184```
185
186
187
188## lpad(str, minLength[, char]):String
189
190Pad string from left with `char` if its' length is smaller than `minLen`.
191
192See: [`rpad()`](#rpad)
193
194### Example
195
196```js
197lpad('a', 5); // " a"
198lpad('a', 5, '-'); // "----a"
199lpad('abc', 3, '-'); // "abc"
200lpad('abc', 4, '-'); // "-abc"
201```
202
203
204
205## ltrim(str, [chars]):String
206
207Remove chars or white-spaces from beginning of string.
208
209`chars` is an array of chars to remove from the beginning of the string. If
210`chars` is not specified, Unicode whitespace chars will be used instead.
211
212See: [`rtrim()`](#rtrim), [`trim()`](#trim)
213
214### Example
215
216```js
217ltrim(' lorem ipsum '); // "lorem ipsum "
218ltrim('--lorem ipsum--', ['-']); // "lorem ipsum--"
219```
220
221
222
223## makePath(...args):String
224
225Group arguments as path segments, if any of the args is `null` or `undefined`
226it will be ignored from resulting path. It will also remove duplicate "/".
227
228See: [`array/join()`](array.html#join)
229
230### Example
231
232```js
233makePath('lorem', 'ipsum', null, 'dolor'); // "lorem/ipsum/dolor"
234makePath('foo///bar/'); // "foo/bar/"
235```
236
237
238
239## normalizeLineBreaks(str, [lineBreak]):String
240
241Normalize line breaks to a single format. Defaults to Unix `\n`.
242
243It handles DOS (`\r\n`), Mac (`\r`) and Unix (`\n`) formats.
244
245### Example
246
247```js
248// "foo\nbar\nlorem\nipsum"
249normalizeLineBreaks('foo\nbar\r\nlorem\ripsum');
250
251// "foo\rbar\rlorem\ripsum"
252normalizeLineBreaks('foo\nbar\r\nlorem\ripsum', '\r');
253
254// "foo bar lorem ipsum"
255normalizeLineBreaks('foo\nbar\r\nlorem\ripsum', ' ');
256```
257
258
259
260## pascalCase(str):String
261
262Convert string to "PascalCase" text.
263
264See: [`camelCase()`](#camelCase)
265
266### Example
267
268```js
269pascalCase('lorem-ipsum-dolor'); // "LoremIpsumDolor"
270pascalCase('lorem ipsum dolor'); // "LoremIpsumDolor"
271```
272
273
274
275## properCase(str):String
276
277UPPERCASE first char of each word, lowercase other chars.
278
279### Example
280
281```js
282properCase('loRem iPSum'); // "Lorem Ipsum"
283```
284
285
286
287## removeNonASCII(str):String
288
289Remove [non-printable ASCII
290chars](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters).
291
292### Example
293
294```js
295removeNonASCII('äÄçÇéÉêlorem-ipsumöÖÐþúÚ'); // "lorem-ipsum"
296```
297
298
299
300## removeNonWord(str):String
301
302Remove non-word chars.
303
304### Example
305
306```js
307var str = 'lorem ~!@#$%^&*()_+`-={}[]|\\:";\'/?><., ipsum';
308removeNonWord(str); // "lorem - ipsum"
309```
310
311
312
313## repeat(str, n):String
314
315Repeat string n-times.
316
317### Example
318
319```js
320repeat('a', 3); // "aaa"
321repeat('bc', 2); // "bcbc"
322repeat('a', 0); // ""
323```
324
325
326
327## replace(str, search, replacements):String
328
329Replace string(s) with the replacement(s) in the source.
330
331`search` and `replacements` can be an array, or a single item. For every item
332in `search`, it will call `str.replace` with the search item and the matching
333replacement in `replacements`. If `replacements` only contains one replacement,
334it will be used for all the searches, otherwise it will use the replacement at
335the same index as the search.
336
337### Example
338
339```js
340replace('foo bar', 'foo', 'test'); // "test bar"
341replace('test 1 2', ['1', '2'], 'n'); // "test n n"
342replace('test 1 2', ['1', '2'], ['one', 'two']); // "test one two"
343replace('123abc', [/\d/g, /[a-z]/g], ['0', '.']); // "000..."
344```
345
346
347
348## replaceAccents(str):String
349
350Replaces all accented chars with regular ones.
351
352**Important:** Only covers **Basic Latin** and **Latin-1** unicode chars.
353
354### Example
355
356```js
357replaceAccents('spéçïãl çhârs'); // "special chars"
358```
359
360
361
362## rpad(str, minLength[, char]):String
363
364Pad string from right with `char` if its' length is smaller than `minLen`.
365
366See: [`lpad()`](#lpad)
367
368### Example
369
370```js
371rpad('a', 5); // "a "
372rpad('a', 5, '-'); // "a----"
373rpad('abc', 3, '-'); // "abc"
374rpad('abc', 4, '-'); // "abc-"
375```
376
377
378
379## rtrim(str, [chars]):String
380
381Remove chars or white-spaces from end of string.
382
383`chars` is an array of chars to remove from the end of the string. If
384`chars` is not specified, Unicode whitespace chars will be used instead.
385
386See: [`trim()`](#trim), [`ltrim()`](#ltrim)
387
388### Example
389
390```js
391rtrim(' lorem ipsum '); // " lorem ipsum"
392rtrim('--lorem ipsum--', ['-']); // "--lorem ipsum"
393```
394
395
396
397## sentenceCase(str):String
398
399UPPERCASE first char of each sentence and lowercase other chars.
400
401### Example
402
403```js
404var str = 'Lorem IpSum DoLOr. maeCeNnas Ullamcor.';
405sentenceCase(str); // "Lorem ipsum dolor. Maecennas ullamcor."
406```
407
408
409
410## stripHtmlTags(str):String
411
412Remove HTML/XML tags from string.
413
414### Example
415
416```js
417var str = '<p><em>lorem</em> <strong>ipsum</strong></p>';
418stripHtmlTags(str); // "lorem ipsum"
419```
420
421
422
423## startsWith(str, prefix):Boolean
424
425Checks if string starts with specified prefix.
426
427See: [`endsWith()`](#endsWith), [`contains()`](#contains)
428
429### Example
430
431```js
432startsWith('lorem ipsum', 'lorem'); // true
433startsWith('lorem ipsum', 'ipsum'); // false
434```
435
436
437
438## slugify(str[, delimiter]):String
439
440Convert to lower case, remove accents, remove non-word chars and replace spaces
441with the delimiter. The default delimiter is a hyphen.
442
443Note that this does not split camelCase text.
444
445See: [`hyphenate()`](#hyphenate) and [`underscore()`](#underscore)
446
447### Example
448
449```js
450var str = 'loremIpsum dolor spéçïãl chârs';
451slugify(str); // "loremipsum-dolor-special-chars"
452slugify(str, '_'); // "loremipsum_dolor_special_chars"
453```
454
455## stripMargin(str[, marginChar]):String
456
457Strip leading characters followed by 'marginChar' from every line in a String.
458The default margin character is a pipe.
459
460### Example
461
462```js
463var str = 'this\n';
464str += ' |is a formatted\n';
465str += ' |string';
466
467
468stripMargin(str); //"this\nis a formatted\nstring"
469stripMargin("this\n___#works\n___#too", '#'); //"this\nworks\ntoo"
470
471```
472
473
474## trim(str, [chars]):String
475
476Remove chars or white-spaces from beginning and end of string.
477
478`chars` is an array of chars to remove from the beginning and end of the
479string. If `chars` is not specified, Unicode whitespace chars will be used
480instead.
481
482See: [`rtrim()`](#rtrim), [`ltrim()`](#ltrim)
483
484### Example
485
486```js
487trim(' lorem ipsum '); // "lorem ipsum"
488trim('-+-lorem ipsum-+-', ['-', '+']); // "lorem ipsum"
489```
490
491
492
493## truncate(str, maxChars, [append], [onlyFullWords]):String
494
495Limit number of chars. Returned string `length` will be `<= maxChars`.
496
497See: [`crop()`](#crop)
498
499### Arguments
500
501 1. `str` (String) : String
502 2. `maxChars` (Number) : Maximum number of characters including `append.length`.
503 3. `[append]` (String) : Value that should be added to the end of string.
504 Defaults to "...".
505 4. `[onlyFullWords]` (Boolean) : If it shouldn't break words. Default is
506 `false`. (favor [`crop()`](#crop) since code will be clearer).
507
508### Example
509
510```js
511truncate('lorem ipsum dolor', 11); // "lorem ip..."
512truncate('lorem ipsum dolor', 11, '+'); // "lorem ipsu+"
513truncate('lorem ipsum dolor', 11, null, true); // "lorem..."
514```
515
516
517
518## typecast(str):*
519
520Parses string and convert it into a native value.
521
522### Example
523
524```js
525typecast('lorem ipsum'); // "lorem ipsum"
526typecast('123'); // 123
527typecast('123.45'); // 123.45
528typecast('false'); // false
529typecast('true'); // true
530typecast('null'); // null
531typecast('undefined'); // undefined
532```
533
534
535
536## unCamelCase(str, [delimiter]):String
537
538Add the delimiter between camelCase text and convert first char of each word to
539lower case.
540
541The delimiter defaults to a space character.
542
543See: [`camelCase()`][#camelCase]
544
545### Example
546
547```js
548unCamelCase('loremIpsumDolor'); // "lorem ipsum dolor"
549unCamelCase('loremIpsumDolor', '-'); // "lorem-ipsum-color"
550```
551
552
553## underscore(str):String
554
555Replaces spaces with underscores, split camelCase text, remove non-word chars,
556remove accents and convert to lower case.
557
558See: [`slugify()`](#slugify), [`hyphenate()`](#hyphenate)
559
560```js
561underscore(' %# lorem ipsum ? $ dolor'); // "lorem_ipsum_dolor"
562underscore('spéçïãl çhârs'); // "special_chars"
563underscore('loremIpsum'); // "lorem_ipsum"
564```
565
566
567
568## unescapeHtml(str):String
569
570Unescapes the following HTML character references back into the raw symbol they map to:
571
572* `&amp;` becomes `&`
573* `&lt;` becomes `<`
574* `&gt;` becomes `>`
575* `&#39;` becomes `'`
576* `&quot;` becomes `"`
577
578No other HTML character references are unescaped. To HTML-unescape other entities as well, use a third-party library like [_he_](http://mths.be/he).
579
580
581See: [`escapeHtml()`](#escapeHtml)
582
583### Example
584
585```js
586unescapeHtml('lorem &amp;amp; &amp;quot;ipsum&amp;quot;'); // 'lorem & "ipsum"'
587```
588
589
590
591## unescapeUnicode(str):String
592
593Unescapes unicode char sequences.
594
595See: [`escapeUnicode()`](#escapeUnicode)
596
597```js
598unescapeUnicode('\\u0066\\u00f8\\u006f\\u0020\\u0062\\u00e5\\u0072');
599// > 'føo bår'
600```
601
602
603
604## unhyphenate(str):String
605
606Replaces hyphens with spaces. (only hyphens between word chars)
607
608See : [`hyphenate()`](#hyphenate)
609
610### Example
611
612```js
613unhyphenate('lorem-ipsum-dolor'); // "lorem ipsum dolor"
614```
615
616
617## upperCase(str):String
618
619"Safer" `String.toUpperCase()`. (Used internally)
620
621### Example
622
623```js
624(null).toUpperCase(); // Error!
625(undefined).toUpperCase(); // Error!
626upperCase(null); // ""
627upperCase(undefined); // ""
628```
629
630
631
632## WHITE_SPACES:Array
633
634Constant array of all [Unicode white-space
635characters](http://en.wikipedia.org/wiki/Whitespace_character).
636
637
638
639-------------------------------------------------------------------------------
640
641For more usage examples check specs inside `/tests` folder. Unit tests are the
642best documentation you can get...