UNPKG

31.2 kBMarkdownView Raw
1[string.js](http://stringjs.com)
2=========
3
4[![build status](https://secure.travis-ci.org/jprichardson/string.js.png)](http://travis-ci.org/jprichardson/string.js)
5
6
7[![Sauce Test Status](https://saucelabs.com/browser-matrix/stringjs.svg)](https://saucelabs.com/u/stringjs)
8
9`string.js`, or simply `S` is a lightweight (**< 5 kb** minified and gzipped) JavaScript library for the browser or for Node.js that provides extra String methods. Originally, it modified the String prototype. But I quickly learned that in JavaScript, this is considered poor practice.
10
11
12
13Why?
14----
15
16Personally, I prefer the cleanliness of the way code looks when it appears to be native methods. i.e. when you modify native JavaScript prototypes. However, if any app dependency required `string.js`, then the app's string prototype would be modified in every module. This could be troublesome. So I settled on creating a wrapper a la jQuery style. For those of you prototype hatin' fools, there is the method `extendPrototype()`.
17
18Here's a list of alternative frameworks:
19
20* [Prototype Framework's String library](http://prototypejs.org/api/string)
21* [Uize.String](http://www.uize.com/reference/Uize.String.html)
22* [Google Closure's String](http://closure-library.googlecode.com/svn/docs/namespace_goog_string.html)
23* [Underscore.string](http://epeli.github.com/underscore.string/)
24* [Sugar.js](http://sugarjs.com)
25* [php.js](http://phpjs.org/functions/)
26
27Why wasn't I happy with any of them? They are all static methods that don't seem to support chaining in a clean way 'OR' they have an odd dependency. Sugar is the notable exception.
28
29
30
31Installation
32------------
33
341. If you want to use this library, you first need to install the [Node.js] (https://nodejs.org/en/).
35
362. When you install node.js, will also be installed [npm] (https://www.npmjs.com/).
37
383. Please run the following command.
39
40```
41npm install --save string
42```
43
44
45Experiment with String.js Now
46-----------------------------
47
48Assuming you're on http://stringjs.com, just simply open up the Webkit inspector in either Chrome or Safari, or the web console in Firefox and you'll notice that `string.js` is included in this page so that you can start experimenting with it right away.
49
50
51
52Usage
53-----
54
55### Node.js
56
57```javascript
58var S = require('string');
59```
60
61Originally, I was using `$s` but glancing over the code, it was easy to confuse `$s` for string.js with `$` for jQuery. Feel free to use the most convenient variable for you.
62
63
64### Rails
65
66Checkout this gem to easily use string.js on the asset pipeline: https://github.com/jesjos/stringjs-rails
67
68
69
70### Browsers
71
72```html
73<!-- HTML5 -->
74<script src="https://cdn.rawgit.com/jprichardson/string.js/master/dist/string.min.js"></script>
75
76<!-- Note that in the mime type for Javascript is now officially 'application/javascript'. If you
77set the type to application/javascript in IE browsers, your Javacript will fail. Just don't set a
78type via the script tag and set the mime type from your server. Most browsers look at the server mime
79type anyway -->
80
81<!-- For HTML4/IE -->
82<script type="text/javascript" src="https://cdn.rawgit.com/jprichardson/string.js/master/dist/string.min.js"></script>
83```
84
85A global variable `window.S` or simply `S` is created.
86
87
88### AMD Support
89
90It now [has AMD support](https://github.com/jprichardson/string.js/pull/20). See [require.js](http://requirejs.org/) on how to use with AMD modules.
91
92
93### Both
94
95```javascript
96var doesIt = S('my cool string').left(2).endsWith('y'); //true
97```
98
99Access the wrapped string using `s` variable or `toString()`
100
101```javascript
102var name = S('Your name is JP').right(2).s; //'JP'
103```
104
105is the same as…
106
107```javascript
108var name = S('Your name is JP').right(2).toString(); //'JP'
109```
110
111Still like the clean look of calling these methods directly on native Strings? No problem. Call `extendPrototype()`. Make sure to not call this at the module level, at it'll effect the entire application lifecycle. You should really only use this at the method level. The one exception being if your application will not be a dependency of another application.
112
113```javascript
114S.extendPrototype();
115var name = 'Your name is JP'.right(2); //'JP'
116S.restorePrototype(); //be a good citizen and clean up
117```
118
119
120### Browser Compatibility
121
122`string.js` has been designed to be compatible with Node.js and with IE6+, Firefox 3+, Safari 2+, Chrome 3+. Please [click here][browsertest] to run the tests in your browser. Report any browser issues here: https://github.com/jprichardson/string.js/issues
123
124
125### Extending string.js
126
127See: https://github.com/jprichardson/string.js/pull/57
128
129
130
131Native JavaScript Methods
132-------------------------
133
134`string.js` imports all of the native JavaScript methods. This is for convenience. The only difference is that the imported methods return `string.js` objects instead of native JavaScript strings. The one exception to this is the method `charAt(index)`. This is because `charAt()` only returns a string of length one. This is typically done for comparisons and a `string.js` object will have little to no value here.
135
136All of the native methods support chaining with the `string.js` methods.
137
138**Example:**
139
140```javascript
141var S = require('string');
142
143var phrase = S('JavaScript is the best scripting language ever!');
144var sub = 'best scripting';
145var pos = phrase.indexOf(sub);
146console.log(phrase.substr(pos, sub.length).truncate(8)); //best...
147```
148
149
150Methods
151-------
152
153See [test file][testfile] for more details.
154
155I use the same nomenclature as Objective-C regarding methods. **+** means `static` or `class` method. **-** means `non-static` or `instance` method.
156
157### - constructor(nativeJsString) ###
158
159This creates a new `string.js` object. The parameter can be anything. The `toString()` method will be called on any objects. Some native objects are used in some functions such as `toCSV()`.
160
161Example:
162
163```javascript
164S('hello').s //"hello"
165S(['a,b']).s //"a,b"
166S({hi: 'jp'}).s //"[object Object]""
167```
168
169
170### - between(left, right)
171
172Extracts a string between `left` and `right` strings.
173
174Example:
175
176```javascript
177S('<a>foo</a>').between('<a>', '</a>').s // => 'foo'
178S('<a>foo</a></a>').between('<a>', '</a>').s // => 'foo'
179S('<a><a>foo</a></a>').between('<a>', '</a>').s // => '<a>foo'
180S('<a>foo').between('<a>', '</a>').s // => ''
181S('Some strings } are very {weird}, dont you think?').between('{', '}').s // => 'weird'
182S('This is a test string').between('test').s // => ' string'
183S('This is a test string').between('', 'test').s // => 'This is a '
184```
185
186### - camelize()
187
188Remove any underscores or dashes and convert a string into camel casing.
189
190Example:
191
192```javascript
193S('data_rate').camelize().s; //'dataRate'
194S('background-color').camelize().s; //'backgroundColor'
195S('-moz-something').camelize().s; //'MozSomething'
196S('_car_speed_').camelize().s; //'CarSpeed'
197S('yes_we_can').camelize().s; //'yesWeCan'
198```
199
200
201### - capitalize() ###
202
203Capitalizes the first character of a string.
204
205Example:
206
207```javascript
208S('jon').capitalize().s; //'Jon'
209S('JP').capitalize().s; //'Jp'
210```
211
212
213### - chompLeft(prefix)
214
215Removes `prefix` from start of string.
216
217Example:
218
219```javascript
220S('foobar').chompLeft('foo').s; //'bar'
221S('foobar').chompLeft('bar').s; //'foobar'
222```
223
224
225### - chompRight(suffix)
226
227Removes `suffix` from end of string.
228
229Example:
230
231```javascript
232S('foobar').chompRight('bar').s; //'foo'
233S('foobar').chompRight('foo').s; //'foobar'
234```
235
236
237### - collapseWhitespace() ###
238
239Converts all adjacent whitespace characters to a single space.
240
241Example:
242
243```javascript
244var str = S(' String \t libraries are \n\n\t fun\n! ').collapseWhitespace().s; //'String libraries are fun !'
245```
246
247
248### - contains(ss) ###
249
250Returns true if the string contains `ss`.
251
252Alias: `include()`
253
254Example:
255
256```javascript
257S('JavaScript is one of the best languages!').contains('one'); //true
258```
259
260
261### - count(substring) ###
262
263Returns the count of the number of occurrences of the substring.
264
265Example:
266
267```javascript
268S('JP likes to program. JP does not play in the NBA.').count("JP")// 2
269S('Does not exist.').count("Flying Spaghetti Monster") //0
270S('Does not exist.').count("Bigfoot") //0
271S('JavaScript is fun, therefore Node.js is fun').count("fun") //2
272S('funfunfun').count("fun") //3
273```
274
275
276### - dasherize() ###
277
278Returns a converted camel cased string into a string delimited by dashes.
279
280Examples:
281
282```javascript
283S('dataRate').dasherize().s; //'data-rate'
284S('CarSpeed').dasherize().s; //'-car-speed'
285S('yesWeCan').dasherize().s; //'yes-we-can'
286S('backgroundColor').dasherize().s; //'background-color'
287```
288
289
290### - decodeHTMLEntities() ###
291
292Decodes HTML entities into their string representation.
293
294```javascript
295S('Ken Thompson &amp; Dennis Ritchie').decodeHTMLEntities().s; //'Ken Thompson & Dennis Ritchie'
296S('3 &lt; 4').decodeHTMLEntities().s; //'3 < 4'
297```
298
299
300### - endsWith(ss) ###
301
302Returns true if the string ends with `ss`.
303
304Example:
305
306```javascript
307S("hello jon").endsWith('jon'); //true
308```
309
310
311### - escapeHTML() ###
312
313Escapes the html.
314
315Example:
316
317```javascript
318S('<div>hi</div>').escapeHTML().s; //&lt;div&gt;hi&lt;/div&gt;
319```
320
321
322### + extendPrototype() ###
323
324Modifies `String.prototype` to have all of the methods found in string.js.
325
326Example:
327
328```javascript
329S.extendPrototype();
330```
331
332
333
334### - ensureLeft(prefix)
335
336Ensures string starts with `prefix`.
337
338Example:
339
340```javascript
341S('subdir').ensureLeft('/').s; //'/subdir'
342S('/subdir').ensureLeft('/').s; //'/subdir'
343```
344
345
346### - ensureRight(suffix)
347
348Ensures string ends with `suffix`.
349
350Example:
351
352```javascript
353S('dir').ensureRight('/').s; //'dir/'
354S('dir/').ensureRight('/').s; //'dir/'
355```
356
357### - humanize() ###
358
359Transforms the input into a human friendly form.
360
361Example:
362
363```javascript
364S('the_humanize_string_method').humanize().s //'The humanize string method'
365S('ThehumanizeStringMethod').humanize().s //'Thehumanize string method'
366S('the humanize string method').humanize().s //'The humanize string method'
367S('the humanize_id string method_id').humanize().s //'The humanize id string method'
368S('the humanize string method ').humanize().s //'The humanize string method'
369S(' capitalize dash-CamelCase_underscore trim ').humanize().s //'Capitalize dash camel case underscore trim'
370```
371
372### - include(ss) ###
373
374Returns true if the string contains the `ss`.
375
376Alias: `contains()`
377
378Example:
379
380```javascript
381S('JavaScript is one of the best languages!').include('one'); //true
382```
383
384
385### - isAlpha() ###
386
387Return true if the string contains only letters.
388
389Example:
390
391```javascript
392S("afaf").isAlpha(); //true
393S('fdafaf3').isAlpha(); //false
394S('dfdf--dfd').isAlpha(); //false
395```
396
397
398### - isAlphaNumeric() ###
399
400Return true if the string contains only letters and numbers
401
402Example:
403
404```javascript
405S("afaf35353afaf").isAlphaNumeric(); //true
406S("FFFF99fff").isAlphaNumeric(); //true
407S("99").isAlphaNumeric(); //true
408S("afff").isAlphaNumeric(); //true
409S("Infinity").isAlphaNumeric(); //true
410S("-Infinity").isAlphaNumeric(); //false
411S("-33").isAlphaNumeric(); //false
412S("aaff..").isAlphaNumeric(); //false
413```
414
415
416### - isEmpty() ###
417
418Return true if the string is solely composed of whitespace or is `null`/`undefined`.
419
420Example:
421
422```javascript
423S(' ').isEmpty(); //true
424S('\t\t\t ').isEmpty(); //true
425S('\n\n ').isEmpty(); //true
426S('helo').isEmpty(); //false
427S(null).isEmpty(); //true
428S(undefined).isEmpty(); //true
429```
430
431
432### - isLower() ###
433
434Return true if the character or string is lowercase
435
436Example:
437
438```javascript
439S('a').isLower(); //true
440S('z').isLower(); //true
441S('B').isLower(); //false
442S('hijp').isLower(); //true
443S('hi jp').isLower(); //false
444S('HelLO').isLower(); //false
445```
446
447
448### - isNumeric() ###
449
450Return true if the string only contains digits
451
452Example:
453
454```javascript
455S("3").isNumeric(); //true
456S("34.22").isNumeric(); //false
457S("-22.33").isNumeric(); //false
458S("NaN").isNumeric(); //false
459S("Infinity").isNumeric(); //false
460S("-Infinity").isNumeric(); //false
461S("JP").isNumeric(); //false
462S("-5").isNumeric(); //false
463S("000992424242").isNumeric(); //true
464```
465
466
467### - isUpper() ###
468
469Returns true if the character or string is uppercase
470
471Example:
472
473```javascript
474S('a').isUpper() //false
475S('z').isUpper() //false
476S('B').isUpper() //true
477S('HIJP').isUpper() //true
478S('HI JP').isUpper() //false
479S('HelLO').isUpper() //true
480```
481
482
483### - latinise() ###
484
485Removes accents from Latin characters.
486
487```javascript
488S('crème brûlée').latinise().s // 'creme brulee'
489```
490
491
492### - left(n) ###
493
494Return the substring denoted by `n` positive left-most characters.
495
496Example:
497
498```javascript
499S('My name is JP').left(2).s; //'My'
500S('Hi').left(0).s; //''
501S('My name is JP').left(-2).s; //'JP', same as right(2)
502```
503
504
505### - length ###
506
507Property to return the length of the string object.
508
509Example:
510
511```javascript
512S('hi').length; //2
513```
514
515### - lines() ####
516
517Returns an array with the lines. Cross-platform compatible.
518
519Example:
520
521```javascript
522var stuff = "My name is JP\nJavaScript is my fav language\r\nWhat is your fav language?"
523var lines = S(stuff).lines()
524
525console.dir(lines)
526/*
527[ 'My name is JP',
528 'JavaScript is my fav language',
529 'What is your fav language?' ]
530*/
531```
532
533
534### - pad(len, [char])
535
536Pads the string in the center with specified character. `char` may be a string or a number, defaults is a space.
537
538Example:
539
540```javascript
541S('hello').pad(5).s //'hello'
542S('hello').pad(10).s //' hello '
543S('hey').pad(7).s //' hey '
544S('hey').pad(5).s //' hey '
545S('hey').pad(4).s //' hey'
546S('hey').pad(7, '-').s//'--hey--'
547```
548
549
550### - padLeft(len, [char])
551
552Left pads the string.
553
554Example:
555
556```javascript
557S('hello').padLeft(5).s //'hello'
558S('hello').padLeft(10).s //' hello'
559S('hello').padLeft(7).s //' hello'
560S('hello').padLeft(6).s //' hello'
561S('hello').padLeft(10, '.').s //'.....hello'
562```
563
564
565### - padRight(len, [char])
566
567Right pads the string.
568
569Example:
570
571```javascript
572S('hello').padRight(5).s //'hello'
573S('hello').padRight(10).s //'hello '
574S('hello').padRight(7).s //'hello '
575S('hello').padRight(6).s //'hello '
576S('hello').padRight(10, '.').s //'hello.....'
577```
578
579
580### - parseCSV() ###
581
582Parses a CSV line into an array.
583
584**Arguments:**
585- `delimiter`: The character that is separates or delimits fields. Default: `,`
586- `qualifier`: The character that encloses fields. Default: `"`
587- `escape`: The character that represents the escape character. Default: `\`
588- `lineDelimiter`: The character that represents the end of a line. When a lineDelimiter is passed the result will be a multidimensional array. Default: `undefined`
589
590Example:
591
592```javascript
593S("'a','b','c'").parseCSV(',', "'") //['a', 'b', 'c'])
594S('"a","b","c"').parseCSV() // ['a', 'b', 'c'])
595S('a,b,c').parseCSV(',', null) //['a', 'b', 'c'])
596S("'a,','b','c'").parseCSV(',', "'") //['a,', 'b', 'c'])
597S('"a","b",4,"c"').parseCSV(',', null) //['"a"', '"b"', '4', '"c"'])
598S('"a","b","4","c"').parseCSV() //['a', 'b', '4', 'c'])
599S('"a","b", "4","c"').parseCSV() //['a', 'b', '4', 'c'])
600S('"a","b", 4,"c"').parseCSV(",", null) //[ '"a"', '"b"', ' 4', '"c"' ])
601S('"a","b\\"","d","c"').parseCSV() //['a', 'b"', 'd', 'c'])
602S('"a","b\\"","d","c"').parseCSV() //['a', 'b"', 'd', 'c'])
603S('"a\na","b","c"\n"a", """b\nb", "a"').parseCSV(',', '"', '"', '\n')) // [ [ 'a\na', 'b', 'c' ], [ 'a', '"b\nb', 'a' ] ]
604```
605
606### - repeat(n) ###
607
608Returns a string repeated `n` times.
609
610Alias: `times()`
611
612Example:
613
614```javascript
615S(' ').repeat(5).s; //' '
616S('*').repeat(3).s; //'***'
617```
618
619
620### - replaceAll(ss, newstr) ###
621
622Return the new string with all occurrences of `ss` replaced with `newstr`.
623
624Example:
625
626```javascript
627S(' does IT work? ').replaceAll(' ', '_').s; //'_does_IT_work?_'
628S('Yes it does!').replaceAll(' ', '').s; //'Yesitdoes!'
629```
630
631
632### + restorePrototype() ###
633
634Restore the original String prototype. Typically used in conjunction with `extendPrototype()`.
635
636Example:
637
638```javascript
639S.restorePrototype();
640```
641
642
643### - right(n) ###
644
645Return the substring denoted by `n` positive right-most characters.
646
647Example:
648
649```javascript
650S('I AM CRAZY').right(2).s; //'ZY'
651S('Does it work? ').right(4).s; //'k? '
652S('Hi').right(0).s; //''
653S('My name is JP').right(-2).s; //'My', same as left(2)
654```
655
656
657### - s ###
658
659Alias: `toString()`
660
661The encapsulated native string representation of an `S` object.
662
663Example:
664
665```javascript
666S('my name is JP.').capitalize().s; //My name is JP.
667var a = "Hello " + S('joe!'); //a = "Hello joe!"
668S("Hello").toString() === S("Hello").s; //true
669```
670
671
672### - setValue(value) ###
673
674Sets the string to a `value`.
675
676```javascript
677var myString = S('War');
678myString.setValue('Peace').s; // 'Peace'
679```
680
681
682### - slugify() ###
683
684Converts the text into a valid url slug. Removes accents from Latin characters.
685
686```javascript
687S('Global Thermonuclear Warfare').slugify().s // 'global-thermonuclear-warfare'
688S('Crème brûlée').slugify().s // 'creme-brulee'
689```
690
691
692### - splitLeft(sep, [maxSplit = -1, [limit]]) ###
693
694Returns an array of strings, split from the left at `sep`. Performs at most `maxSplit` splits, and slices the result into an array with at most `limit` elements.
695
696Example:
697
698```javascript
699S('We built this city').splitLeft(' '); // ['We', 'built', 'this', 'city'];
700S('We built this city').splitLeft(' ', 1); // ['We', 'built this city'];
701S('On Rock N Roll and other Stuff').splitLeft(' ', -1, 4); // ['On', 'Rock', 'N', 'Roll'];
702S('On Rock N Roll and other Stuff').splitLeft(' ', 5, -2); // ['and', 'other Stuff'];
703```
704
705
706### - splitRight(sep, [maxSplit = -1, [limit]]) ###
707
708Returns an array of strings, split from the left at `sep`. Performs at most `maxSplit` splits, and slices the result into an array with at most `limit` elements.
709
710Example:
711
712```javascript
713S('This is all very fun').splitRight(' '); // ['This', 'is', 'all', 'very', 'fun'];
714S('and I could do it forever').splitRight(' ', 1); // ['and I could do it', 'forever'];
715S('but nothing matters in the end.').splitRight(' ', -1, 2); // ['the', 'end.'];
716S('but nothing matters in the end.').splitRight(' ', 4, -2); // ['but nothing', 'matters'];
717```
718
719
720### - startsWith(prefix) ###
721
722Return true if the string starts with `prefix`.
723
724Example:
725
726```javascript
727S('JP is a software engineer').startsWith('JP'); //true
728S('wants to change the world').startsWith('politicians'); //false
729```
730
731
732### - strip([string1],[string2],...) ###
733
734Returns a new string with all occurrences of `[string1],[string2],...` removed.
735
736Example:
737
738```javascript
739S(' 1 2 3--__--4 5 6-7__8__9--0').strip(' ', '_', '-').s; //'1234567890'
740S('can words also be stripped out?').strip('words', 'also', 'be').s; //'can stripped out?'
741```
742
743### - stripLeft([chars]) ###
744Returns a new string in which all chars have been stripped from the beginning of the string (default whitespace characters).
745
746Example:
747
748```javascript
749S(' hello ').stripLeft().s; //'hello '
750S('abcz').stripLeft('a-z').s; //'bcz'
751S('www.example.com').stripLeft('w.').s; //'example.com'
752```
753
754### - stripRight([chars]) ###
755Returns a new string in which all chars have been stripped from the end of the string (default whitespace characters).
756
757Example:
758
759```javascript
760S(' hello ').stripRight().s; //' hello'
761S('abcz').stripRight('a-z').s; //'abc'
762```
763
764
765### - stripPunctuation()
766
767Strip all of the punctuation.
768
769Example:
770
771```javascript
772S('My, st[ring] *full* of %punct)').stripPunctuation().s; //My string full of punct
773```
774
775
776
777### - stripTags([tag1],[tag2],...) ###
778
779Strip all of the HTML tags or tags specified by the parameters.
780
781Example:
782
783```javascript
784S('<p>just <b>some</b> text</p>').stripTags().s //'just some text'
785S('<p>just <b>some</b> text</p>').stripTags('p').s //'just <b>some</b> text'
786```
787
788
789### - template(values, [open], [close])
790
791Takes a string and interpolates the values. Defaults to `{{` and `}}` for Mustache compatible templates. However, you can change this default by modifying `S.TMPL_OPEN` and `S.TMPL_CLOSE`.
792
793Example:
794
795```js
796var str = "Hello {{name}}! How are you doing during the year of {{date-year}}?"
797var values = {name: 'JP', 'date-year': 2013}
798console.log(S(str).template(values).s) //'Hello JP! How are you doing during the year of 2013?'
799
800str = "Hello #{name}! How are you doing during the year of #{date-year}?"
801console.log(S(str).template(values, '#{', '}').s) //'Hello JP! How are you doing during the year of 2013?'
802
803S.TMPL_OPEN = '{'
804S.TMPL_CLOSE = '}'
805str = "Hello {name}! How are you doing during the year of {date-year}?"
806console.log(S(str).template(values).s) //'Hello JP! How are you doing during the year of 2013?'
807```
808
809
810### - times(n) ###
811
812Returns a string repeated `n` times.
813
814Alias: `repeat()`
815
816Example:
817
818```javascript
819S(' ').times(5).s //' '
820S('*').times(3).s //'***'
821```
822
823
824### - titleCase() ###
825
826Returns a string with the first letter of each word uppercased, including hyphenated words
827
828Example:
829
830```javascript
831S('Like ice in the sunshine').titleCase().s // 'Like Ice In The Sunshine'
832S('data_rate').titleCase().s // 'Data_Rate'
833S('background-color').titleCase().s // 'Background-Color'
834S('-moz-something').titleCase().s // '-Moz-Something'
835S('_car_speed_').titleCase().s // '_Car_Speed_'
836S('yes_we_can').titleCase().s // 'Yes_We_Can
837
838S(' capitalize dash-CamelCase_underscore trim ').humanize().titleCase().s // 'Capitalize Dash Camel Case Underscore Trim'
839```
840
841
842### - toBoolean() / toBool()
843
844Converts a a logical truth string to boolean. That is: `true`, `1`, `'true'`, `'on'`, or `'yes'`.
845
846JavaScript Note: You can easily convert truthy values to `booleans` by prefixing them with `!!`. e.g.
847`!!'hi' === true` or `!!'' === false` or `!!{} === true`.
848
849Example:
850
851```javascript
852S('true').toBoolean() //true
853S('false').toBoolean() //false
854S('hello').toBoolean() //false
855S(true).toBoolean() //true
856S('on').toBoolean() //true
857S('yes').toBoolean() //true
858S('TRUE').toBoolean() //true
859S('TrUe').toBoolean() //true
860S('YES').toBoolean() //true
861S('ON').toBoolean() //true
862S('').toBoolean() //false
863S(undefined).toBoolean() //false
864S('undefined').toBoolean() //false
865S(null).toBoolean() //false
866S(false).toBoolean() //false
867S({}).toBoolean() //false
868S(1).toBoolean() //true
869S(-1).toBoolean() //false
870S(0).toBoolean() //false
871```
872
873
874
875### - toCSV(options) ###
876
877Converts an array or object to a CSV line.
878
879You can either optionally pass in two string arguments or pass in a configuration object.
880
881**String Arguments:**
882- `delimiter`: The character that is separates or delimits fields. Default: `,`
883- `qualifier`: The character that encloses fields. Default: `"`
884
885
886**Object Configuration:**
887- `delimiter`: The character that is separates or delimits fields. Default: `,`
888- `qualifier`: The character that encloses fields. Default: `"`
889- `escape`: The character that escapes any incline `qualifier` characters. Default: `\`, in JS this is `\\`
890- `encloseNumbers`: Enclose number objects with the `qualifier` character. Default: `true`
891- `keys`: If the input isn't an array, but an object, then if this is set to true, the keys will be output to the CSV line, otherwise it's the object's values. Default: `false`.
892
893Example:
894
895```javascript
896S(['a', 'b', 'c']).toCSV().s //'"a","b","c"'
897S(['a', 'b', 'c']).toCSV(':').s //'"a":"b":"c"'
898S(['a', 'b', 'c']).toCSV(':', null).s //'a:b:c')
899S(['a', 'b', 'c']).toCSV('*', "'").s //"'a'*'b'*'c'"
900S(['a"', 'b', 4, 'c']).toCSV({delimiter: ',', qualifier: '"', escape: '\\', encloseNumbers: false}).s //'"a\\"","b",4,"c"'
901S({firstName: 'JP', lastName: 'Richardson'}).toCSV({keys: true}).s //'"firstName","lastName"'
902S({firstName: 'JP', lastName: 'Richardson'}).toCSV().s //'"JP","Richardson"'
903```
904
905
906### - toFloat([precision]) ###
907
908Return the float value, wraps parseFloat.
909
910Example:
911
912```javascript
913S('5').toFloat() // 5
914S('5.3').toFloat() //5.3
915S(5.3).toFloat() //5.3
916S('-10').toFloat() //-10
917S('55.3 adfafaf').toFloat() // 55.3
918S('afff 44').toFloat() //NaN
919S(3.45522222333232).toFloat(2) // 3.46
920```
921
922
923### - toInt() / toInteger() ###
924
925Return the number value in integer form. Wrapper for `parseInt()`. Can also parse hex values.
926
927Example:
928
929```javascript
930S('5').toInt(); //5
931S('5.3').toInt(); //5;
932S(5.3).toInt(); //5;
933S('-10').toInt(); //-10
934S('55 adfafaf').toInt(); //55
935S('afff 44').toInt(); //NaN
936S('0xff').toInt() //255
937```
938
939
940
941### - toString() ###
942
943Alias: `s`
944
945Return the string representation of an `S` object. Not really necessary to use. However, JS engines will look at an object and display its `toString()` result.
946
947Example:
948
949```javascript
950S('my name is JP.').capitalize().toString(); //My name is JP.
951var a = "Hello " + S('joe!'); //a = "Hello joe!"
952S("Hello").toString() === S("Hello").s; //true
953```
954
955
956### - trim() ###
957
958Return the string with leading and trailing whitespace removed. Reverts to native `trim()` if it exists.
959
960Example:
961
962```javascript
963S('hello ').trim().s; //'hello'
964S(' hello ').trim().s; //'hello'
965S('\nhello').trim().s; //'hello'
966S('\nhello\r\n').trim().s; //'hello'
967S('\thello\t').trim().s; //'hello'
968```
969
970
971### - trimLeft() ###
972
973Return the string with leading and whitespace removed
974
975Example:
976
977```javascript
978S(' How are you?').trimLeft().s; //'How are you?';
979```
980
981
982### - trimRight() ###
983
984Return the string with trailing whitespace removed.
985
986Example:
987
988```javascript
989S('How are you? ').trimRight().s; //'How are you?';
990```
991
992
993### - truncate(length, [chars]) ###
994
995Truncates the string, accounting for word placement and character count.
996
997Example:
998
999```javascript
1000S('this is some long text').truncate(3).s //'...'
1001S('this is some long text').truncate(7).s //'this is...'
1002S('this is some long text').truncate(11).s //'this is...'
1003S('this is some long text').truncate(12).s //'this is some...'
1004S('this is some long text').truncate(11).s //'this is...'
1005S('this is some long text').truncate(14, ' read more').s //'this is some read more'
1006```
1007
1008
1009
1010### - underscore()
1011
1012Returns converted camel cased string into a string delimited by underscores.
1013
1014Example:
1015
1016```javascript
1017S('dataRate').underscore().s; //'data_rate'
1018S('CarSpeed').underscore().s; //'car_speed'
1019S('yesWeCan').underscore().s; //'yes_we_can'
1020```
1021
1022
1023### - unescapeHTML() ###
1024
1025Unescapes the html.
1026
1027Example:
1028
1029```javascript
1030S('&lt;div&gt;hi&lt;/div&gt;').unescapeHTML().s; //<div>hi</div>
1031```
1032
1033### - wrapHTML() ###
1034
1035wrapHTML helps to avoid concatenation of element with string.
1036the string will be wrapped with HTML Element and their attributes.
1037
1038Example:
1039```javascript
1040S('Venkat').wrapHTML().s //<span>Venkat</span>
1041S('Venkat').wrapHTML('div').s //<div>Venkat</div>
1042S('Venkat').wrapHTML('div', {
1043 "class": "left bullet"
1044}).s //<div class="left bullet">Venkat</div>
1045S('Venkat').wrapHTML('div', {
1046 "id": "content",
1047 "class": "left bullet"
1048}).s // <div id="content" class="left bullet">Venkat</div>
1049```
1050
1051### + VERSION ###
1052
1053Returns native JavaScript string containing the version of `string.js`.
1054
1055Example:
1056
1057```javascript
1058S.VERSION; //1.0.0
1059```
1060
1061
1062Quirks
1063------
1064
1065`decodeHtmlEntities()` converts `&nbsp;` to **0xa0** (160) and not **0x10** (20). Most browsers consider 0xa0 to be whitespace characters, Internet Explorer does not despite it being part of the ECMA standard. Google Closure does a good job of normalizing this behavior. This may need to be fixed in `string.js` at some point in time.
1066
1067
1068
1069Testing
1070-------
1071
1072### Node.js
1073
1074Install the dev dependencies:
1075
1076 $ npm install string --development
1077
1078Install mocha globally:
1079
1080 $ npm install -g mocha
1081
1082Then navigate to the installed directory:
1083
1084 $ cd node_modules/string/
1085
1086Run test package:
1087
1088 $ mocha test
1089
1090
1091
1092### Browser ###
1093
1094[Click here to run the tests in your web browser.][browsertest]
1095
1096
1097
1098Credits
1099-------
1100
1101I have looked at the code by the creators in the libraries mentioned in **Motivation**. As noted in the source code, I've specifically used code from Google Closure (Google Inc), Underscore String [Esa-Matti Suuronen](http://esa-matti.suuronen.org/), and php.js (http://phpjs.org/authors/index), [Substack](https://github.com/substack/node-ent) and [TJ Holowaychuk](https://github.com/component/pad).
1102
1103
1104
1105Contributions
1106-------------
1107
1108If you contribute to this library, just modify `string.js`, `string.test.js`, and update `README.md`. I'll update the website docs and generate the new `string.min.js`, changelog and version.
1109
1110
1111### Contributors
1112
1113(You can add your name, or I'll add it if you forget)
1114
1115- [*] [JP Richardson](https://github.com/jprichardson)
1116- [4] [Azharul Islam](https://github.com/az7arul)
1117- [3] [Sergio Muriel](https://github.com/Sergio-Muriel)
1118- [1] [Venkatraman.R](https://github.com/ramsunvtech)
1119- [1] [r3Fuze](https://github.com/r3Fuze)
1120- [1] [Matt Hickford](https://github.com/hickford)
1121- [1] [Petr Brzek](https://github.com/petrbrzek)
1122- [1] [Alex Zinchenko](https://github.com/yumitsu)
1123- [1] [Guy Ellis](https://github.com/guyellis)
1124- [*] [Leonardo Otero](https://github.com/oteroleonardo)
1125- [*] [Jordan Scales](https://github.com/prezjordan)
1126- [*] [Eduardo de Matos](https://github.com/eduardo-matos)
1127- [*] [Christian Maughan Tegnér](https://github.com/CMTegner)
1128- [*] [Mario Gutierrez](https://github.com/mgutz)
1129- [*] [Sean O'Dell](https://github.com/seanodell)
1130- [*] [Tim de Koning](https://github.com/Reggino)
1131- [*] [David Volm](https://github.com/daxxog)
1132- [*] [Jeff Grann](https://github.com/jeffgrann)
1133- [*] [Vlad GURDIGA](https://github.com/gurdiga)
1134- [*] [Jon Principe](https://github.com/jprincipe)
1135- [*] [James Manning](https://github.com/jamesmanning)
1136- [*] [Nathan Friedly](https://github.com/nfriedly)
1137- [*] [Alison Rowland](https://github.com/arowla)
1138- [*] [Pascal Bihler](https://github.com/pbihler)
1139- [*] [Daniel Diekmeier](https://github.com/danieldiekmeier)
1140
1141
1142
1143Roadmap to v2.0
1144---------------
1145- break up this module into smaller logically grouped modules. The Node.js version would probably always include most of the functions. https://github.com/jprichardson/string.js/issues/10
1146- allow a more functional style similar to Underscore and Lodash. This may introduce a `chain` function though. https://github.com/jprichardson/string.js/issues/49
1147- language specific plugins i.e. https://github.com/jprichardson/string.js/pull/46
1148- move this repo over to https://github.com/stringjs
1149
1150
1151
1152License
1153-------
1154
1155Licensed under MIT.
1156
1157Copyright (C) 2012-2016 JP Richardson <jprichardson@gmail.com>
1158
1159Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
1160
1161The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
1162
1163THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1164
1165
1166
1167
1168[testfile]: https://github.com/jprichardson/string.js/blob/master/test/string.test.js
1169[browsertest]: http://stringjs.com/browser.test.html
1170
1171[aboutjp]: http://about.me/jprichardson
1172[twitter]: http://twitter.com/jprichardson
1173[procbits]: http://procbits.com