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 |
|
13 | Why?
|
14 | ----
|
15 |
|
16 | Personally, 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 |
|
18 | Here'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 |
|
27 | Why 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 |
|
31 | Installation
|
32 | ------------
|
33 |
|
34 | 1. If you want to use this library, you first need to install the [Node.js] (https://nodejs.org/en/).
|
35 |
|
36 | 2. When you install node.js, will also be installed [npm] (https://www.npmjs.com/).
|
37 |
|
38 | 3. Please run the following command.
|
39 |
|
40 | ```
|
41 | npm install --save string
|
42 | ```
|
43 |
|
44 |
|
45 | Experiment with String.js Now
|
46 | -----------------------------
|
47 |
|
48 | Assuming 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 |
|
52 | Usage
|
53 | -----
|
54 |
|
55 | ### Node.js
|
56 |
|
57 | ```javascript
|
58 | var S = require('string');
|
59 | ```
|
60 |
|
61 | Originally, 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 |
|
66 | Checkout 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
|
77 | set the type to application/javascript in IE browsers, your Javacript will fail. Just don't set a
|
78 | type via the script tag and set the mime type from your server. Most browsers look at the server mime
|
79 | type 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 |
|
85 | A global variable `window.S` or simply `S` is created.
|
86 |
|
87 |
|
88 | ### AMD Support
|
89 |
|
90 | It 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
|
96 | var doesIt = S('my cool string').left(2).endsWith('y'); //true
|
97 | ```
|
98 |
|
99 | Access the wrapped string using `s` variable or `toString()`
|
100 |
|
101 | ```javascript
|
102 | var name = S('Your name is JP').right(2).s; //'JP'
|
103 | ```
|
104 |
|
105 | is the same as…
|
106 |
|
107 | ```javascript
|
108 | var name = S('Your name is JP').right(2).toString(); //'JP'
|
109 | ```
|
110 |
|
111 | Still 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
|
114 | S.extendPrototype();
|
115 | var name = 'Your name is JP'.right(2); //'JP'
|
116 | S.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 |
|
127 | See: https://github.com/jprichardson/string.js/pull/57
|
128 |
|
129 |
|
130 |
|
131 | Native 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 |
|
136 | All of the native methods support chaining with the `string.js` methods.
|
137 |
|
138 | **Example:**
|
139 |
|
140 | ```javascript
|
141 | var S = require('string');
|
142 |
|
143 | var phrase = S('JavaScript is the best scripting language ever!');
|
144 | var sub = 'best scripting';
|
145 | var pos = phrase.indexOf(sub);
|
146 | console.log(phrase.substr(pos, sub.length).truncate(8)); //best...
|
147 | ```
|
148 |
|
149 |
|
150 | Methods
|
151 | -------
|
152 |
|
153 | See [test file][testfile] for more details.
|
154 |
|
155 | I 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 |
|
159 | This 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 |
|
161 | Example:
|
162 |
|
163 | ```javascript
|
164 | S('hello').s //"hello"
|
165 | S(['a,b']).s //"a,b"
|
166 | S({hi: 'jp'}).s //"[object Object]""
|
167 | ```
|
168 |
|
169 |
|
170 | ### - between(left, right)
|
171 |
|
172 | Extracts a string between `left` and `right` strings.
|
173 |
|
174 | Example:
|
175 |
|
176 | ```javascript
|
177 | S('<a>foo</a>').between('<a>', '</a>').s // => 'foo'
|
178 | S('<a>foo</a></a>').between('<a>', '</a>').s // => 'foo'
|
179 | S('<a><a>foo</a></a>').between('<a>', '</a>').s // => '<a>foo'
|
180 | S('<a>foo').between('<a>', '</a>').s // => ''
|
181 | S('Some strings } are very {weird}, dont you think?').between('{', '}').s // => 'weird'
|
182 | S('This is a test string').between('test').s // => ' string'
|
183 | S('This is a test string').between('', 'test').s // => 'This is a '
|
184 | ```
|
185 |
|
186 | ### - camelize()
|
187 |
|
188 | Remove any underscores or dashes and convert a string into camel casing.
|
189 |
|
190 | Example:
|
191 |
|
192 | ```javascript
|
193 | S('data_rate').camelize().s; //'dataRate'
|
194 | S('background-color').camelize().s; //'backgroundColor'
|
195 | S('-moz-something').camelize().s; //'MozSomething'
|
196 | S('_car_speed_').camelize().s; //'CarSpeed'
|
197 | S('yes_we_can').camelize().s; //'yesWeCan'
|
198 | ```
|
199 |
|
200 |
|
201 | ### - capitalize() ###
|
202 |
|
203 | Capitalizes the first character of a string.
|
204 |
|
205 | Example:
|
206 |
|
207 | ```javascript
|
208 | S('jon').capitalize().s; //'Jon'
|
209 | S('JP').capitalize().s; //'Jp'
|
210 | ```
|
211 |
|
212 |
|
213 | ### - chompLeft(prefix)
|
214 |
|
215 | Removes `prefix` from start of string.
|
216 |
|
217 | Example:
|
218 |
|
219 | ```javascript
|
220 | S('foobar').chompLeft('foo').s; //'bar'
|
221 | S('foobar').chompLeft('bar').s; //'foobar'
|
222 | ```
|
223 |
|
224 |
|
225 | ### - chompRight(suffix)
|
226 |
|
227 | Removes `suffix` from end of string.
|
228 |
|
229 | Example:
|
230 |
|
231 | ```javascript
|
232 | S('foobar').chompRight('bar').s; //'foo'
|
233 | S('foobar').chompRight('foo').s; //'foobar'
|
234 | ```
|
235 |
|
236 |
|
237 | ### - collapseWhitespace() ###
|
238 |
|
239 | Converts all adjacent whitespace characters to a single space.
|
240 |
|
241 | Example:
|
242 |
|
243 | ```javascript
|
244 | var str = S(' String \t libraries are \n\n\t fun\n! ').collapseWhitespace().s; //'String libraries are fun !'
|
245 | ```
|
246 |
|
247 |
|
248 | ### - contains(ss) ###
|
249 |
|
250 | Returns true if the string contains `ss`.
|
251 |
|
252 | Alias: `include()`
|
253 |
|
254 | Example:
|
255 |
|
256 | ```javascript
|
257 | S('JavaScript is one of the best languages!').contains('one'); //true
|
258 | ```
|
259 |
|
260 |
|
261 | ### - count(substring) ###
|
262 |
|
263 | Returns the count of the number of occurrences of the substring.
|
264 |
|
265 | Example:
|
266 |
|
267 | ```javascript
|
268 | S('JP likes to program. JP does not play in the NBA.').count("JP")// 2
|
269 | S('Does not exist.').count("Flying Spaghetti Monster") //0
|
270 | S('Does not exist.').count("Bigfoot") //0
|
271 | S('JavaScript is fun, therefore Node.js is fun').count("fun") //2
|
272 | S('funfunfun').count("fun") //3
|
273 | ```
|
274 |
|
275 |
|
276 | ### - dasherize() ###
|
277 |
|
278 | Returns a converted camel cased string into a string delimited by dashes.
|
279 |
|
280 | Examples:
|
281 |
|
282 | ```javascript
|
283 | S('dataRate').dasherize().s; //'data-rate'
|
284 | S('CarSpeed').dasherize().s; //'-car-speed'
|
285 | S('yesWeCan').dasherize().s; //'yes-we-can'
|
286 | S('backgroundColor').dasherize().s; //'background-color'
|
287 | ```
|
288 |
|
289 |
|
290 | ### - decodeHTMLEntities() ###
|
291 |
|
292 | Decodes HTML entities into their string representation.
|
293 |
|
294 | ```javascript
|
295 | S('Ken Thompson & Dennis Ritchie').decodeHTMLEntities().s; //'Ken Thompson & Dennis Ritchie'
|
296 | S('3 < 4').decodeHTMLEntities().s; //'3 < 4'
|
297 | ```
|
298 |
|
299 |
|
300 | ### - endsWith(ss) ###
|
301 |
|
302 | Returns true if the string ends with `ss`.
|
303 |
|
304 | Example:
|
305 |
|
306 | ```javascript
|
307 | S("hello jon").endsWith('jon'); //true
|
308 | ```
|
309 |
|
310 |
|
311 | ### - escapeHTML() ###
|
312 |
|
313 | Escapes the html.
|
314 |
|
315 | Example:
|
316 |
|
317 | ```javascript
|
318 | S('<div>hi</div>').escapeHTML().s; //<div>hi</div>
|
319 | ```
|
320 |
|
321 |
|
322 | ### + extendPrototype() ###
|
323 |
|
324 | Modifies `String.prototype` to have all of the methods found in string.js.
|
325 |
|
326 | Example:
|
327 |
|
328 | ```javascript
|
329 | S.extendPrototype();
|
330 | ```
|
331 |
|
332 |
|
333 |
|
334 | ### - ensureLeft(prefix)
|
335 |
|
336 | Ensures string starts with `prefix`.
|
337 |
|
338 | Example:
|
339 |
|
340 | ```javascript
|
341 | S('subdir').ensureLeft('/').s; //'/subdir'
|
342 | S('/subdir').ensureLeft('/').s; //'/subdir'
|
343 | ```
|
344 |
|
345 |
|
346 | ### - ensureRight(suffix)
|
347 |
|
348 | Ensures string ends with `suffix`.
|
349 |
|
350 | Example:
|
351 |
|
352 | ```javascript
|
353 | S('dir').ensureRight('/').s; //'dir/'
|
354 | S('dir/').ensureRight('/').s; //'dir/'
|
355 | ```
|
356 |
|
357 | ### - humanize() ###
|
358 |
|
359 | Transforms the input into a human friendly form.
|
360 |
|
361 | Example:
|
362 |
|
363 | ```javascript
|
364 | S('the_humanize_string_method').humanize().s //'The humanize string method'
|
365 | S('ThehumanizeStringMethod').humanize().s //'Thehumanize string method'
|
366 | S('the humanize string method').humanize().s //'The humanize string method'
|
367 | S('the humanize_id string method_id').humanize().s //'The humanize id string method'
|
368 | S('the humanize string method ').humanize().s //'The humanize string method'
|
369 | S(' capitalize dash-CamelCase_underscore trim ').humanize().s //'Capitalize dash camel case underscore trim'
|
370 | ```
|
371 |
|
372 | ### - include(ss) ###
|
373 |
|
374 | Returns true if the string contains the `ss`.
|
375 |
|
376 | Alias: `contains()`
|
377 |
|
378 | Example:
|
379 |
|
380 | ```javascript
|
381 | S('JavaScript is one of the best languages!').include('one'); //true
|
382 | ```
|
383 |
|
384 |
|
385 | ### - isAlpha() ###
|
386 |
|
387 | Return true if the string contains only letters.
|
388 |
|
389 | Example:
|
390 |
|
391 | ```javascript
|
392 | S("afaf").isAlpha(); //true
|
393 | S('fdafaf3').isAlpha(); //false
|
394 | S('dfdf--dfd').isAlpha(); //false
|
395 | ```
|
396 |
|
397 |
|
398 | ### - isAlphaNumeric() ###
|
399 |
|
400 | Return true if the string contains only letters and numbers
|
401 |
|
402 | Example:
|
403 |
|
404 | ```javascript
|
405 | S("afaf35353afaf").isAlphaNumeric(); //true
|
406 | S("FFFF99fff").isAlphaNumeric(); //true
|
407 | S("99").isAlphaNumeric(); //true
|
408 | S("afff").isAlphaNumeric(); //true
|
409 | S("Infinity").isAlphaNumeric(); //true
|
410 | S("-Infinity").isAlphaNumeric(); //false
|
411 | S("-33").isAlphaNumeric(); //false
|
412 | S("aaff..").isAlphaNumeric(); //false
|
413 | ```
|
414 |
|
415 |
|
416 | ### - isEmpty() ###
|
417 |
|
418 | Return true if the string is solely composed of whitespace or is `null`/`undefined`.
|
419 |
|
420 | Example:
|
421 |
|
422 | ```javascript
|
423 | S(' ').isEmpty(); //true
|
424 | S('\t\t\t ').isEmpty(); //true
|
425 | S('\n\n ').isEmpty(); //true
|
426 | S('helo').isEmpty(); //false
|
427 | S(null).isEmpty(); //true
|
428 | S(undefined).isEmpty(); //true
|
429 | ```
|
430 |
|
431 |
|
432 | ### - isLower() ###
|
433 |
|
434 | Return true if the character or string is lowercase
|
435 |
|
436 | Example:
|
437 |
|
438 | ```javascript
|
439 | S('a').isLower(); //true
|
440 | S('z').isLower(); //true
|
441 | S('B').isLower(); //false
|
442 | S('hijp').isLower(); //true
|
443 | S('hi jp').isLower(); //false
|
444 | S('HelLO').isLower(); //false
|
445 | ```
|
446 |
|
447 |
|
448 | ### - isNumeric() ###
|
449 |
|
450 | Return true if the string only contains digits
|
451 |
|
452 | Example:
|
453 |
|
454 | ```javascript
|
455 | S("3").isNumeric(); //true
|
456 | S("34.22").isNumeric(); //false
|
457 | S("-22.33").isNumeric(); //false
|
458 | S("NaN").isNumeric(); //false
|
459 | S("Infinity").isNumeric(); //false
|
460 | S("-Infinity").isNumeric(); //false
|
461 | S("JP").isNumeric(); //false
|
462 | S("-5").isNumeric(); //false
|
463 | S("000992424242").isNumeric(); //true
|
464 | ```
|
465 |
|
466 |
|
467 | ### - isUpper() ###
|
468 |
|
469 | Returns true if the character or string is uppercase
|
470 |
|
471 | Example:
|
472 |
|
473 | ```javascript
|
474 | S('a').isUpper() //false
|
475 | S('z').isUpper() //false
|
476 | S('B').isUpper() //true
|
477 | S('HIJP').isUpper() //true
|
478 | S('HI JP').isUpper() //false
|
479 | S('HelLO').isUpper() //true
|
480 | ```
|
481 |
|
482 |
|
483 | ### - latinise() ###
|
484 |
|
485 | Removes accents from Latin characters.
|
486 |
|
487 | ```javascript
|
488 | S('crème brûlée').latinise().s // 'creme brulee'
|
489 | ```
|
490 |
|
491 |
|
492 | ### - left(n) ###
|
493 |
|
494 | Return the substring denoted by `n` positive left-most characters.
|
495 |
|
496 | Example:
|
497 |
|
498 | ```javascript
|
499 | S('My name is JP').left(2).s; //'My'
|
500 | S('Hi').left(0).s; //''
|
501 | S('My name is JP').left(-2).s; //'JP', same as right(2)
|
502 | ```
|
503 |
|
504 |
|
505 | ### - length ###
|
506 |
|
507 | Property to return the length of the string object.
|
508 |
|
509 | Example:
|
510 |
|
511 | ```javascript
|
512 | S('hi').length; //2
|
513 | ```
|
514 |
|
515 | ### - lines() ####
|
516 |
|
517 | Returns an array with the lines. Cross-platform compatible.
|
518 |
|
519 | Example:
|
520 |
|
521 | ```javascript
|
522 | var stuff = "My name is JP\nJavaScript is my fav language\r\nWhat is your fav language?"
|
523 | var lines = S(stuff).lines()
|
524 |
|
525 | console.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 |
|
536 | Pads the string in the center with specified character. `char` may be a string or a number, defaults is a space.
|
537 |
|
538 | Example:
|
539 |
|
540 | ```javascript
|
541 | S('hello').pad(5).s //'hello'
|
542 | S('hello').pad(10).s //' hello '
|
543 | S('hey').pad(7).s //' hey '
|
544 | S('hey').pad(5).s //' hey '
|
545 | S('hey').pad(4).s //' hey'
|
546 | S('hey').pad(7, '-').s//'--hey--'
|
547 | ```
|
548 |
|
549 |
|
550 | ### - padLeft(len, [char])
|
551 |
|
552 | Left pads the string.
|
553 |
|
554 | Example:
|
555 |
|
556 | ```javascript
|
557 | S('hello').padLeft(5).s //'hello'
|
558 | S('hello').padLeft(10).s //' hello'
|
559 | S('hello').padLeft(7).s //' hello'
|
560 | S('hello').padLeft(6).s //' hello'
|
561 | S('hello').padLeft(10, '.').s //'.....hello'
|
562 | ```
|
563 |
|
564 |
|
565 | ### - padRight(len, [char])
|
566 |
|
567 | Right pads the string.
|
568 |
|
569 | Example:
|
570 |
|
571 | ```javascript
|
572 | S('hello').padRight(5).s //'hello'
|
573 | S('hello').padRight(10).s //'hello '
|
574 | S('hello').padRight(7).s //'hello '
|
575 | S('hello').padRight(6).s //'hello '
|
576 | S('hello').padRight(10, '.').s //'hello.....'
|
577 | ```
|
578 |
|
579 |
|
580 | ### - parseCSV() ###
|
581 |
|
582 | Parses 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 |
|
590 | Example:
|
591 |
|
592 | ```javascript
|
593 | S("'a','b','c'").parseCSV(',', "'") //['a', 'b', 'c'])
|
594 | S('"a","b","c"').parseCSV() // ['a', 'b', 'c'])
|
595 | S('a,b,c').parseCSV(',', null) //['a', 'b', 'c'])
|
596 | S("'a,','b','c'").parseCSV(',', "'") //['a,', 'b', 'c'])
|
597 | S('"a","b",4,"c"').parseCSV(',', null) //['"a"', '"b"', '4', '"c"'])
|
598 | S('"a","b","4","c"').parseCSV() //['a', 'b', '4', 'c'])
|
599 | S('"a","b", "4","c"').parseCSV() //['a', 'b', '4', 'c'])
|
600 | S('"a","b", 4,"c"').parseCSV(",", null) //[ '"a"', '"b"', ' 4', '"c"' ])
|
601 | S('"a","b\\"","d","c"').parseCSV() //['a', 'b"', 'd', 'c'])
|
602 | S('"a","b\\"","d","c"').parseCSV() //['a', 'b"', 'd', 'c'])
|
603 | S('"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 |
|
608 | Returns a string repeated `n` times.
|
609 |
|
610 | Alias: `times()`
|
611 |
|
612 | Example:
|
613 |
|
614 | ```javascript
|
615 | S(' ').repeat(5).s; //' '
|
616 | S('*').repeat(3).s; //'***'
|
617 | ```
|
618 |
|
619 |
|
620 | ### - replaceAll(ss, newstr) ###
|
621 |
|
622 | Return the new string with all occurrences of `ss` replaced with `newstr`.
|
623 |
|
624 | Example:
|
625 |
|
626 | ```javascript
|
627 | S(' does IT work? ').replaceAll(' ', '_').s; //'_does_IT_work?_'
|
628 | S('Yes it does!').replaceAll(' ', '').s; //'Yesitdoes!'
|
629 | ```
|
630 |
|
631 |
|
632 | ### + restorePrototype() ###
|
633 |
|
634 | Restore the original String prototype. Typically used in conjunction with `extendPrototype()`.
|
635 |
|
636 | Example:
|
637 |
|
638 | ```javascript
|
639 | S.restorePrototype();
|
640 | ```
|
641 |
|
642 |
|
643 | ### - right(n) ###
|
644 |
|
645 | Return the substring denoted by `n` positive right-most characters.
|
646 |
|
647 | Example:
|
648 |
|
649 | ```javascript
|
650 | S('I AM CRAZY').right(2).s; //'ZY'
|
651 | S('Does it work? ').right(4).s; //'k? '
|
652 | S('Hi').right(0).s; //''
|
653 | S('My name is JP').right(-2).s; //'My', same as left(2)
|
654 | ```
|
655 |
|
656 |
|
657 | ### - s ###
|
658 |
|
659 | Alias: `toString()`
|
660 |
|
661 | The encapsulated native string representation of an `S` object.
|
662 |
|
663 | Example:
|
664 |
|
665 | ```javascript
|
666 | S('my name is JP.').capitalize().s; //My name is JP.
|
667 | var a = "Hello " + S('joe!'); //a = "Hello joe!"
|
668 | S("Hello").toString() === S("Hello").s; //true
|
669 | ```
|
670 |
|
671 |
|
672 | ### - setValue(value) ###
|
673 |
|
674 | Sets the string to a `value`.
|
675 |
|
676 | ```javascript
|
677 | var myString = S('War');
|
678 | myString.setValue('Peace').s; // 'Peace'
|
679 | ```
|
680 |
|
681 |
|
682 | ### - slugify() ###
|
683 |
|
684 | Converts the text into a valid url slug. Removes accents from Latin characters.
|
685 |
|
686 | ```javascript
|
687 | S('Global Thermonuclear Warfare').slugify().s // 'global-thermonuclear-warfare'
|
688 | S('Crème brûlée').slugify().s // 'creme-brulee'
|
689 | ```
|
690 |
|
691 |
|
692 | ### - splitLeft(sep, [maxSplit = -1, [limit]]) ###
|
693 |
|
694 | Returns 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 |
|
696 | Example:
|
697 |
|
698 | ```javascript
|
699 | S('We built this city').splitLeft(' '); // ['We', 'built', 'this', 'city'];
|
700 | S('We built this city').splitLeft(' ', 1); // ['We', 'built this city'];
|
701 | S('On Rock N Roll and other Stuff').splitLeft(' ', -1, 4); // ['On', 'Rock', 'N', 'Roll'];
|
702 | S('On Rock N Roll and other Stuff').splitLeft(' ', 5, -2); // ['and', 'other Stuff'];
|
703 | ```
|
704 |
|
705 |
|
706 | ### - splitRight(sep, [maxSplit = -1, [limit]]) ###
|
707 |
|
708 | Returns 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 |
|
710 | Example:
|
711 |
|
712 | ```javascript
|
713 | S('This is all very fun').splitRight(' '); // ['This', 'is', 'all', 'very', 'fun'];
|
714 | S('and I could do it forever').splitRight(' ', 1); // ['and I could do it', 'forever'];
|
715 | S('but nothing matters in the end.').splitRight(' ', -1, 2); // ['the', 'end.'];
|
716 | S('but nothing matters in the end.').splitRight(' ', 4, -2); // ['but nothing', 'matters'];
|
717 | ```
|
718 |
|
719 |
|
720 | ### - startsWith(prefix) ###
|
721 |
|
722 | Return true if the string starts with `prefix`.
|
723 |
|
724 | Example:
|
725 |
|
726 | ```javascript
|
727 | S('JP is a software engineer').startsWith('JP'); //true
|
728 | S('wants to change the world').startsWith('politicians'); //false
|
729 | ```
|
730 |
|
731 |
|
732 | ### - strip([string1],[string2],...) ###
|
733 |
|
734 | Returns a new string with all occurrences of `[string1],[string2],...` removed.
|
735 |
|
736 | Example:
|
737 |
|
738 | ```javascript
|
739 | S(' 1 2 3--__--4 5 6-7__8__9--0').strip(' ', '_', '-').s; //'1234567890'
|
740 | S('can words also be stripped out?').strip('words', 'also', 'be').s; //'can stripped out?'
|
741 | ```
|
742 |
|
743 | ### - stripLeft([chars]) ###
|
744 | Returns a new string in which all chars have been stripped from the beginning of the string (default whitespace characters).
|
745 |
|
746 | Example:
|
747 |
|
748 | ```javascript
|
749 | S(' hello ').stripLeft().s; //'hello '
|
750 | S('abcz').stripLeft('a-z').s; //'bcz'
|
751 | S('www.example.com').stripLeft('w.').s; //'example.com'
|
752 | ```
|
753 |
|
754 | ### - stripRight([chars]) ###
|
755 | Returns a new string in which all chars have been stripped from the end of the string (default whitespace characters).
|
756 |
|
757 | Example:
|
758 |
|
759 | ```javascript
|
760 | S(' hello ').stripRight().s; //' hello'
|
761 | S('abcz').stripRight('a-z').s; //'abc'
|
762 | ```
|
763 |
|
764 |
|
765 | ### - stripPunctuation()
|
766 |
|
767 | Strip all of the punctuation.
|
768 |
|
769 | Example:
|
770 |
|
771 | ```javascript
|
772 | S('My, st[ring] *full* of %punct)').stripPunctuation().s; //My string full of punct
|
773 | ```
|
774 |
|
775 |
|
776 |
|
777 | ### - stripTags([tag1],[tag2],...) ###
|
778 |
|
779 | Strip all of the HTML tags or tags specified by the parameters.
|
780 |
|
781 | Example:
|
782 |
|
783 | ```javascript
|
784 | S('<p>just <b>some</b> text</p>').stripTags().s //'just some text'
|
785 | S('<p>just <b>some</b> text</p>').stripTags('p').s //'just <b>some</b> text'
|
786 | ```
|
787 |
|
788 |
|
789 | ### - template(values, [open], [close])
|
790 |
|
791 | Takes 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 |
|
793 | Example:
|
794 |
|
795 | ```js
|
796 | var str = "Hello {{name}}! How are you doing during the year of {{date-year}}?"
|
797 | var values = {name: 'JP', 'date-year': 2013}
|
798 | console.log(S(str).template(values).s) //'Hello JP! How are you doing during the year of 2013?'
|
799 |
|
800 | str = "Hello #{name}! How are you doing during the year of #{date-year}?"
|
801 | console.log(S(str).template(values, '#{', '}').s) //'Hello JP! How are you doing during the year of 2013?'
|
802 |
|
803 | S.TMPL_OPEN = '{'
|
804 | S.TMPL_CLOSE = '}'
|
805 | str = "Hello {name}! How are you doing during the year of {date-year}?"
|
806 | console.log(S(str).template(values).s) //'Hello JP! How are you doing during the year of 2013?'
|
807 | ```
|
808 |
|
809 |
|
810 | ### - times(n) ###
|
811 |
|
812 | Returns a string repeated `n` times.
|
813 |
|
814 | Alias: `repeat()`
|
815 |
|
816 | Example:
|
817 |
|
818 | ```javascript
|
819 | S(' ').times(5).s //' '
|
820 | S('*').times(3).s //'***'
|
821 | ```
|
822 |
|
823 |
|
824 | ### - titleCase() ###
|
825 |
|
826 | Returns a string with the first letter of each word uppercased, including hyphenated words
|
827 |
|
828 | Example:
|
829 |
|
830 | ```javascript
|
831 | S('Like ice in the sunshine').titleCase().s // 'Like Ice In The Sunshine'
|
832 | S('data_rate').titleCase().s // 'Data_Rate'
|
833 | S('background-color').titleCase().s // 'Background-Color'
|
834 | S('-moz-something').titleCase().s // '-Moz-Something'
|
835 | S('_car_speed_').titleCase().s // '_Car_Speed_'
|
836 | S('yes_we_can').titleCase().s // 'Yes_We_Can
|
837 |
|
838 | S(' capitalize dash-CamelCase_underscore trim ').humanize().titleCase().s // 'Capitalize Dash Camel Case Underscore Trim'
|
839 | ```
|
840 |
|
841 |
|
842 | ### - toBoolean() / toBool()
|
843 |
|
844 | Converts a a logical truth string to boolean. That is: `true`, `1`, `'true'`, `'on'`, or `'yes'`.
|
845 |
|
846 | JavaScript Note: You can easily convert truthy values to `booleans` by prefixing them with `!!`. e.g.
|
847 | `!!'hi' === true` or `!!'' === false` or `!!{} === true`.
|
848 |
|
849 | Example:
|
850 |
|
851 | ```javascript
|
852 | S('true').toBoolean() //true
|
853 | S('false').toBoolean() //false
|
854 | S('hello').toBoolean() //false
|
855 | S(true).toBoolean() //true
|
856 | S('on').toBoolean() //true
|
857 | S('yes').toBoolean() //true
|
858 | S('TRUE').toBoolean() //true
|
859 | S('TrUe').toBoolean() //true
|
860 | S('YES').toBoolean() //true
|
861 | S('ON').toBoolean() //true
|
862 | S('').toBoolean() //false
|
863 | S(undefined).toBoolean() //false
|
864 | S('undefined').toBoolean() //false
|
865 | S(null).toBoolean() //false
|
866 | S(false).toBoolean() //false
|
867 | S({}).toBoolean() //false
|
868 | S(1).toBoolean() //true
|
869 | S(-1).toBoolean() //false
|
870 | S(0).toBoolean() //false
|
871 | ```
|
872 |
|
873 |
|
874 |
|
875 | ### - toCSV(options) ###
|
876 |
|
877 | Converts an array or object to a CSV line.
|
878 |
|
879 | You 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 |
|
893 | Example:
|
894 |
|
895 | ```javascript
|
896 | S(['a', 'b', 'c']).toCSV().s //'"a","b","c"'
|
897 | S(['a', 'b', 'c']).toCSV(':').s //'"a":"b":"c"'
|
898 | S(['a', 'b', 'c']).toCSV(':', null).s //'a:b:c')
|
899 | S(['a', 'b', 'c']).toCSV('*', "'").s //"'a'*'b'*'c'"
|
900 | S(['a"', 'b', 4, 'c']).toCSV({delimiter: ',', qualifier: '"', escape: '\\', encloseNumbers: false}).s //'"a\\"","b",4,"c"'
|
901 | S({firstName: 'JP', lastName: 'Richardson'}).toCSV({keys: true}).s //'"firstName","lastName"'
|
902 | S({firstName: 'JP', lastName: 'Richardson'}).toCSV().s //'"JP","Richardson"'
|
903 | ```
|
904 |
|
905 |
|
906 | ### - toFloat([precision]) ###
|
907 |
|
908 | Return the float value, wraps parseFloat.
|
909 |
|
910 | Example:
|
911 |
|
912 | ```javascript
|
913 | S('5').toFloat() // 5
|
914 | S('5.3').toFloat() //5.3
|
915 | S(5.3).toFloat() //5.3
|
916 | S('-10').toFloat() //-10
|
917 | S('55.3 adfafaf').toFloat() // 55.3
|
918 | S('afff 44').toFloat() //NaN
|
919 | S(3.45522222333232).toFloat(2) // 3.46
|
920 | ```
|
921 |
|
922 |
|
923 | ### - toInt() / toInteger() ###
|
924 |
|
925 | Return the number value in integer form. Wrapper for `parseInt()`. Can also parse hex values.
|
926 |
|
927 | Example:
|
928 |
|
929 | ```javascript
|
930 | S('5').toInt(); //5
|
931 | S('5.3').toInt(); //5;
|
932 | S(5.3).toInt(); //5;
|
933 | S('-10').toInt(); //-10
|
934 | S('55 adfafaf').toInt(); //55
|
935 | S('afff 44').toInt(); //NaN
|
936 | S('0xff').toInt() //255
|
937 | ```
|
938 |
|
939 |
|
940 |
|
941 | ### - toString() ###
|
942 |
|
943 | Alias: `s`
|
944 |
|
945 | Return 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 |
|
947 | Example:
|
948 |
|
949 | ```javascript
|
950 | S('my name is JP.').capitalize().toString(); //My name is JP.
|
951 | var a = "Hello " + S('joe!'); //a = "Hello joe!"
|
952 | S("Hello").toString() === S("Hello").s; //true
|
953 | ```
|
954 |
|
955 |
|
956 | ### - trim() ###
|
957 |
|
958 | Return the string with leading and trailing whitespace removed. Reverts to native `trim()` if it exists.
|
959 |
|
960 | Example:
|
961 |
|
962 | ```javascript
|
963 | S('hello ').trim().s; //'hello'
|
964 | S(' hello ').trim().s; //'hello'
|
965 | S('\nhello').trim().s; //'hello'
|
966 | S('\nhello\r\n').trim().s; //'hello'
|
967 | S('\thello\t').trim().s; //'hello'
|
968 | ```
|
969 |
|
970 |
|
971 | ### - trimLeft() ###
|
972 |
|
973 | Return the string with leading and whitespace removed
|
974 |
|
975 | Example:
|
976 |
|
977 | ```javascript
|
978 | S(' How are you?').trimLeft().s; //'How are you?';
|
979 | ```
|
980 |
|
981 |
|
982 | ### - trimRight() ###
|
983 |
|
984 | Return the string with trailing whitespace removed.
|
985 |
|
986 | Example:
|
987 |
|
988 | ```javascript
|
989 | S('How are you? ').trimRight().s; //'How are you?';
|
990 | ```
|
991 |
|
992 |
|
993 | ### - truncate(length, [chars]) ###
|
994 |
|
995 | Truncates the string, accounting for word placement and character count.
|
996 |
|
997 | Example:
|
998 |
|
999 | ```javascript
|
1000 | S('this is some long text').truncate(3).s //'...'
|
1001 | S('this is some long text').truncate(7).s //'this is...'
|
1002 | S('this is some long text').truncate(11).s //'this is...'
|
1003 | S('this is some long text').truncate(12).s //'this is some...'
|
1004 | S('this is some long text').truncate(11).s //'this is...'
|
1005 | S('this is some long text').truncate(14, ' read more').s //'this is some read more'
|
1006 | ```
|
1007 |
|
1008 |
|
1009 |
|
1010 | ### - underscore()
|
1011 |
|
1012 | Returns converted camel cased string into a string delimited by underscores.
|
1013 |
|
1014 | Example:
|
1015 |
|
1016 | ```javascript
|
1017 | S('dataRate').underscore().s; //'data_rate'
|
1018 | S('CarSpeed').underscore().s; //'car_speed'
|
1019 | S('yesWeCan').underscore().s; //'yes_we_can'
|
1020 | ```
|
1021 |
|
1022 |
|
1023 | ### - unescapeHTML() ###
|
1024 |
|
1025 | Unescapes the html.
|
1026 |
|
1027 | Example:
|
1028 |
|
1029 | ```javascript
|
1030 | S('<div>hi</div>').unescapeHTML().s; //<div>hi</div>
|
1031 | ```
|
1032 |
|
1033 | ### - wrapHTML() ###
|
1034 |
|
1035 | wrapHTML helps to avoid concatenation of element with string.
|
1036 | the string will be wrapped with HTML Element and their attributes.
|
1037 |
|
1038 | Example:
|
1039 | ```javascript
|
1040 | S('Venkat').wrapHTML().s //<span>Venkat</span>
|
1041 | S('Venkat').wrapHTML('div').s //<div>Venkat</div>
|
1042 | S('Venkat').wrapHTML('div', {
|
1043 | "class": "left bullet"
|
1044 | }).s //<div class="left bullet">Venkat</div>
|
1045 | S('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 |
|
1053 | Returns native JavaScript string containing the version of `string.js`.
|
1054 |
|
1055 | Example:
|
1056 |
|
1057 | ```javascript
|
1058 | S.VERSION; //1.0.0
|
1059 | ```
|
1060 |
|
1061 |
|
1062 | Quirks
|
1063 | ------
|
1064 |
|
1065 | `decodeHtmlEntities()` converts ` ` 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 |
|
1069 | Testing
|
1070 | -------
|
1071 |
|
1072 | ### Node.js
|
1073 |
|
1074 | Install the dev dependencies:
|
1075 |
|
1076 | $ npm install string --development
|
1077 |
|
1078 | Install mocha globally:
|
1079 |
|
1080 | $ npm install -g mocha
|
1081 |
|
1082 | Then navigate to the installed directory:
|
1083 |
|
1084 | $ cd node_modules/string/
|
1085 |
|
1086 | Run 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 |
|
1098 | Credits
|
1099 | -------
|
1100 |
|
1101 | I 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 |
|
1105 | Contributions
|
1106 | -------------
|
1107 |
|
1108 | If 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 |
|
1143 | Roadmap 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 |
|
1152 | License
|
1153 | -------
|
1154 |
|
1155 | Licensed under MIT.
|
1156 |
|
1157 | Copyright (C) 2012-2016 JP Richardson <jprichardson@gmail.com>
|
1158 |
|
1159 | Permission 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 |
|
1161 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
1162 |
|
1163 | THE 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
|