Blame view
node_modules/underscore.string/README.markdown
20.9 KB
f7563de62
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 |
<span class="github-only"> The stable release documentation can be found here https://epeli.github.io/underscore.string/ </span> # Underscore.string [](http://travis-ci.org/epeli/underscore.string) # Javascript lacks complete string manipulation operations. This is an attempt to fill that gap. List of build-in methods can be found for example from [Dive Into JavaScript][d]. Originally started as an Underscore.js extension but is a full standalone library nowadays. Upgrading from 2.x to 3.x? Please read the [changelog][c]. [c]: https://github.com/epeli/underscore.string/blob/master/CHANGELOG.markdown#300 ## Usage ### For Node.js, Browserify and Webpack Install from npm npm install underscore.string Require individual functions ```javascript var slugify = require("underscore.string/slugify"); slugify("Hello world!"); // => hello-world ``` or load the full library to enable chaining ```javascript var s = require("underscore.string"); s(" epeli ").trim().capitalize().value(); // => "Epeli" ``` but especially when using with [Browserify][] the individual function approach is recommended because using it you only add those functions to your bundle you use. [Browserify]: http://browserify.org/ ### In Meteor From your [Meteor][] project folder ```shell meteor add underscorestring:underscore.string ``` and you'll be able to access the library with the ***s*** global from both the server and the client. ```javascript s.slugify("Hello world!"); // => hello-world s(" epeli ").trim().capitalize().value(); // => "Epeli" ``` [Meteor]: http://www.meteor.com/ ### Others The `dist/underscore.string.js` file is an [UMD][] build. You can load it using an AMD loader such as [RequireJS][] or just stick it to a web page and access the library from the ***s*** global. [UMD]: https://github.com/umdjs/umd [RequireJS]: http://requirejs.org/ ### Underscore.js/Lo-Dash integration It is still possible use as Underscore.js/Lo-Dash extension ```javascript _.mixin(s.exports()); ``` But it's not recommended since `include`, `contains`, `reverse` and `join` are dropped because they collide with the functions already defined by Underscore.js. ### Lo-Dash-FP/Ramda integration If you want to use underscore.string with [ramdajs](http://ramdajs.com/) or [Lo-Dash-FP](https://github.com/lodash/lodash-fp) you can use [underscore.string.fp](https://github.com/stoeffel/underscore.string.fp). npm install underscore.string.fp ```javascript var S = require('underscore.string.fp'); var filter = require('lodash-fp').filter; var filter = require('ramda').filter; filter(S.startsWith('.'), [ '.vimrc', 'foo.md', '.zshrc' ]); // => ['.vimrc', '.zshrc'] ``` ## Download * [Development version](https://npmcdn.com/underscore.string/dist/underscore.string.js) *Uncompressed with Comments* * [Production version](https://npmcdn.com/underscore.string/dist/underscore.string.min.js) *Minified* ## API ### Individual functions #### numberFormat(number, [ decimals=0, decimalSeparator='.', orderSeparator=',']) => string Formats the numbers. ```javascript numberFormat(1000, 2); // => "1,000.00" numberFormat(123456789.123, 5, ".", ","); // => "123,456,789.12300" ``` #### levenshtein(string1, string2) => number Calculates [Levenshtein distance][ld] between two strings. [ld]: http://en.wikipedia.org/wiki/Levenshtein_distance ```javascript levenshtein("kitten", "kittah"); // => 2 ``` #### capitalize(string, [lowercaseRest=false]) => string Converts first letter of the string to uppercase. If `true` is passed as second argument the rest of the string will be converted to lower case. ```javascript capitalize("foo Bar"); // => "Foo Bar" capitalize("FOO Bar", true); // => "Foo bar" ``` #### decapitalize(string) => string Converts first letter of the string to lowercase. ```javascript decapitalize("Foo Bar"); // => "foo Bar" ``` #### chop(string, step) => array ```javascript chop("whitespace", 3); // => ["whi", "tes", "pac", "e"] ``` #### clean(string) => string Trim and replace multiple spaces with a single space. ```javascript clean(" foo bar "); // => "foo bar" ``` #### cleanDiacritics(string) => string Replace [diacritic][dc] characters with closest ASCII equivalents. Check the [source][s] for supported characters. [Pull requests][p] welcome for missing characters! [dc]: https://en.wikipedia.org/wiki/Diacritic [s]: https://github.com/epeli/underscore.string/blob/master/cleanDiacritics.js [p]: https://github.com/epeli/underscore.string/blob/master/CONTRIBUTING.markdown ```javascript cleanDiacritics("ääkkönen"); // => "aakkonen" ``` #### chars(string) => array ```javascript chars("Hello"); // => ["H", "e", "l", "l", "o"] ``` #### swapCase(string) => string Returns a copy of the string in which all the case-based characters have had their case swapped. ```javascript swapCase("hELLO"); // => "Hello" ``` #### include(string, substring) => boolean Tests if string contains a substring. ```javascript include("foobar", "ob"); // => true ``` #### count(string, substring) => number Returns number of occurrences of substring in string. ```javascript count("Hello world", "l"); // => 3 ``` #### escapeHTML(string) => string Converts HTML special characters to their entity equivalents. This function supports cent, yen, euro, pound, lt, gt, copy, reg, quote, amp, apos. ```javascript escapeHTML("<div>Blah blah blah</div>"); // => "<div>Blah blah blah</div>" ``` #### unescapeHTML(string) => string Converts entity characters to HTML equivalents. This function supports cent, yen, euro, pound, lt, gt, copy, reg, quote, amp, apos, nbsp. ```javascript unescapeHTML("<div>Blah blah blah</div>"); // => "<div>Blah blah blah</div>" ``` #### insert(string, index, substring) => string ```javascript insert("Hellworld", 4, "o "); // => "Hello world" ``` #### replaceAll(string, find, replace, [ignorecase=false]) => string ```javascript replaceAll("foo", "o", "a"); // => "faa" ``` #### isBlank(string) => boolean ```javascript isBlank(""); // => true isBlank(" "); // => true isBlank(" "); // => true isBlank("a"); // => false ``` #### join(separator, ...strings) => string Joins strings together with given separator ```javascript join(" ", "foo", "bar"); // => "foo bar" ``` #### lines(str) => array Split lines to an array ```javascript lines("Hello World"); // => ["Hello", "World"] ``` #### wrap(str, options) => string Splits a line `str` (default '') into several lines of size `options.width` (default 75) using a `options.seperator` (default ' '). If `options.trailingSpaces` is true, make each line at least `width` long using trailing spaces. If `options.cut` is true, create new lines in the middle of words. If `options.preserveSpaces` is true, preserve the space that should be there at the end of a line (only works if options.cut is false). ```javascript wrap("Hello World", { width:5 }) // => "Hello World" wrap("Hello World", { width:6, seperator:'.', trailingSpaces: true }) // => "Hello .World " wrap("Hello World", { width:5, seperator:'.', cut:true, trailingSpaces: true }) // => "Hello. Worl.d " wrap("Hello World", { width:5, seperator:'.', preserveSpaces: true }) // => "Hello .World" ``` #### dedent(str, [pattern]) => string Dedent unnecessary indentation or dedent by a pattern. Credits go to @sindresorhus. This implementation is similar to https://github.com/sindresorhus/strip-indent ```javascript dedent(" Hello World"); // => "Hello World" dedent("\t\tHello \t\t\t\tWorld"); // => "Hello \t\tWorld" dedent(" Hello World", " "); // Dedent by 2 spaces // => " Hello World" ``` #### reverse(string) => string Return reversed string: ```javascript reverse("foobar"); // => "raboof" ``` #### splice(string, index, howmany, substring) => string Like an array splice. ```javascript splice("https://edtsech@bitbucket.org/edtsech/underscore.strings", 30, 7, "epeli"); // => "https://edtsech@bitbucket.org/epeli/underscore.strings" ``` #### startsWith(string, starts, [position]) => boolean This method checks whether the string begins with `starts` at `position` (default: 0). ```javascript startsWith("image.gif", "image"); // => true startsWith(".vimrc", "vim", 1); // => true ``` #### endsWith(string, ends, [position]) => boolean This method checks whether the string ends with `ends` at `position` (default: string.length). ```javascript endsWith("image.gif", "gif"); // => true endsWith("image.old.gif", "old", 9); // => true ``` #### pred(string) => string Returns the predecessor to str. ```javascript pred("b"); // => "a" pred("B"); // => "A" ``` #### succ(string) => string Returns the successor to str. ```javascript succ("a"); // => "b" succ("A"); // => "B" ``` #### titleize(string) => string ```javascript titleize("my name is epeli"); // => "My Name Is Epeli" ``` #### camelize(string, [decapitalize=false]) => string Converts underscored or dasherized string to a camelized one. Begins with a lower case letter unless it starts with an underscore, dash or an upper case letter. ```javascript camelize("moz-transform"); // => "mozTransform" camelize("-moz-transform"); // => "MozTransform" camelize("_moz_transform"); // => "MozTransform" camelize("Moz-transform"); // => "MozTransform" camelize("-moz-transform", true); // => "mozTransform" ``` #### classify(string) => string Converts string to camelized class name. First letter is always upper case ```javascript classify("some_class_name"); // => "SomeClassName" ``` #### underscored(string) => string Converts a camelized or dasherized string into an underscored one ```javascript underscored("MozTransform"); // => "moz_transform" ``` #### dasherize(string) => string Converts a underscored or camelized string into an dasherized one ```javascript dasherize("MozTransform"); // => "-moz-transform" ``` #### humanize(string) => string Converts an underscored, camelized, or dasherized string into a humanized one. Also removes beginning and ending whitespace, and removes the postfix '_id'. ```javascript humanize(" capitalize dash-CamelCase_underscore trim "); // => "Capitalize dash camel case underscore trim" ``` #### trim(string, [characters]) => string Trims defined characters from begining and ending of the string. Defaults to whitespace characters. ```javascript trim(" foobar "); // => "foobar" trim("_-foobar-_", "_-"); // => "foobar" ``` #### ltrim(string, [characters]) => string Left trim. Similar to trim, but only for left side. #### rtrim(string, [characters]) => string Right trim. Similar to trim, but only for right side. #### truncate(string, length, [truncateString = '...']) => string ```javascript truncate("Hello world", 5); // => "Hello..." truncate("Hello", 10); // => "Hello" ``` #### prune(string, length, pruneString) => string Elegant version of truncate. Makes sure the pruned string does not exceed the original length. Avoid half-chopped words when truncating. ```javascript prune("Hello, world", 5); // => "Hello..." prune("Hello, world", 8); // => "Hello..." prune("Hello, world", 5, " (read a lot more)"); // => "Hello, world" (as adding "(read a lot more)" would be longer than the original string) prune("Hello, cruel world", 15); // => "Hello, cruel..." prune("Hello", 10); // => "Hello" ``` #### words(str, delimiter=/\s+/) => array Split string by delimiter (String or RegExp), /\s+/ by default. ```javascript words(" I love you "); // => ["I", "love", "you"] words("I_love_you", "_"); // => ["I", "love", "you"] words("I-love-you", /-/); // => ["I", "love", "you"] words(" ") // => [] ``` #### sprintf(string format, ...arguments) => string C like string formatting. Makes use of the [sprintf-js](https://npmjs.org/package/sprintf-js) package. **This function will be removed in the next major release, use the [sprintf-js](https://npmjs.org/package/sprintf-js) package instead.** ```javascript sprintf("%.1f", 1.17); // => "1.2" ``` #### pad(str, length, [padStr, type]) => string pads the `str` with characters until the total string length is equal to the passed `length` parameter. By default, pads on the **left** with the space char (`" "`). `padStr` is truncated to a single character if necessary. ```javascript pad("1", 8); // => " 1" pad("1", 8, "0"); // => "00000001" pad("1", 8, "0", "right"); // => "10000000" pad("1", 8, "0", "both"); // => "00001000" pad("1", 8, "bleepblorp", "both"); // => "bbbb1bbb" ``` #### lpad(str, length, [padStr]) => string left-pad a string. Alias for `pad(str, length, padStr, "left")` ```javascript lpad("1", 8, "0"); // => "00000001" ``` #### rpad(str, length, [padStr]) => string right-pad a string. Alias for `pad(str, length, padStr, "right")` ```javascript rpad("1", 8, "0"); // => "10000000" ``` #### lrpad(str, length, [padStr]) => string left/right-pad a string. Alias for `pad(str, length, padStr, "both")` ```javascript lrpad("1", 8, '0'); // => "00001000" ``` #### toNumber(string, [decimals]) => number Parse string to number. Returns NaN if string can't be parsed to number. ```javascript toNumber("2.556"); // => 3 toNumber("2.556", 1); // => 2.6 toNumber("999.999", -1); // => 990 ``` #### strRight(string, pattern) => string Searches a string from left to right for a pattern and returns a substring consisting of the characters in the string that are to the right of the pattern or all string if no match found. ```javascript strRight("This_is_a_test_string", "_"); // => "is_a_test_string" ``` #### strRightBack(string, pattern) => string Searches a string from right to left for a pattern and returns a substring consisting of the characters in the string that are to the right of the pattern or all string if no match found. ```javascript strRightBack("This_is_a_test_string", "_"); // => "string" ``` #### strLeft(string, pattern) => string Searches a string from left to right for a pattern and returns a substring consisting of the characters in the string that are to the left of the pattern or all string if no match found. ```javascript strLeft("This_is_a_test_string", "_"); // => "This"; ``` #### strLeftBack(string, pattern) => string Searches a string from right to left for a pattern and returns a substring consisting of the characters in the string that are to the left of the pattern or all string if no match found. ```javascript strLeftBack("This_is_a_test_string", "_"); // => "This_is_a_test"; ``` #### stripTags(string) => string Removes all html tags from string. ```javascript stripTags("a <a href=\"#\">link</a>"); // => "a link" stripTags("a <a href=\"#\">link</a><script>alert(\"hello world!\")</script>"); // => "a linkalert("hello world!")" ``` #### toSentence(array, [delimiter, lastDelimiter]) => string Join an array into a human readable sentence. ```javascript toSentence(["jQuery", "Mootools", "Prototype"]); // => "jQuery, Mootools and Prototype"; toSentence(["jQuery", "Mootools", "Prototype"], ", ", " unt "); // => "jQuery, Mootools unt Prototype"; ``` #### toSentenceSerial(array, [delimiter, lastDelimiter]) => string The same as `toSentence`, but adjusts delimeters to use [Serial comma](http://en.wikipedia.org/wiki/Serial_comma). ```javascript toSentenceSerial(["jQuery", "Mootools"]); // => "jQuery and Mootools" toSentenceSerial(["jQuery", "Mootools", "Prototype"]); // => "jQuery, Mootools, and Prototype" toSentenceSerial(["jQuery", "Mootools", "Prototype"], ", ", " unt "); // => "jQuery, Mootools, unt Prototype" ``` #### repeat(string, count, [separator]) => string Repeats a string count times. ```javascript repeat("foo", 3); // => "foofoofoo" repeat("foo", 3, "bar"); // => "foobarfoobarfoo" ``` #### surround(string, wrap) => string Surround a string with another string. ```javascript surround("foo", "ab"); // => "abfooab" ``` #### quote(string, quoteChar) or q(string, quoteChar) => string Quotes a string. `quoteChar` defaults to `"`. ```javascript quote("foo", '"'); // => '"foo"'; ``` #### unquote(string, quoteChar) => string Unquotes a string. `quoteChar` defaults to `"`. ```javascript unquote('"foo"'); // => "foo" unquote("'foo'", "'"); // => "foo" ``` #### slugify(string) => string Transform text into an ascii slug which can be used in safely in URLs. Replaces whitespaces, accentuated, and special characters with a dash. Limited set of non-ascii characters are transformed to similar versions in the ascii character set such as `ä` to `a`. ```javascript slugify("Un éléphant à l\'orée du bois"); // => "un-elephant-a-l-oree-du-bois" ``` ***Caution: this function is charset dependent*** #### naturalCmp(string1, string2) => number Naturally sort strings like humans would do. None numbers are compared by their [ASCII values](http://www.asciitable.com/). Note: this means "a" > "A". Use `.toLowerCase` if this isn't to be desired. Just past it to `Array#sort`. ```javascript ["foo20", "foo5"].sort(naturalCmp); // => ["foo5", "foo20"] ``` #### toBoolean(string) => boolean Turn strings that can be commonly considered as booleas to real booleans. Such as "true", "false", "1" and "0". This function is case insensitive. ```javascript toBoolean("true"); // => true toBoolean("FALSE"); // => false toBoolean("random"); // => undefined ``` It can be customized by giving arrays of truth and falsy value matcher as parameters. Matchers can be also RegExp objects. ```javascript toBoolean("truthy", ["truthy"], ["falsy"]); // => true toBoolean("true only at start", [/^true/]); // => true ``` #### map(string, function) => string Creates a new string with the results of calling a provided function on every character of the given string. ```javascript map("Hello world", function(x) { return x; }); // => "Hello world" map(12345, function(x) { return x; }); // => "12345" map("Hello world", function(x) { if (x === 'o') x = 'O'; return x; }); // => "HellO wOrld" ``` ### Library functions If you require the full library you can use chaining and aliases #### s(string) => chain Start a chain. Returns an immutable chain object with the string functions as methods which return a new chain object instead of the plain string value. The chain object includes also following native Javascript string methods: - [toUpperCase](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) - [toLowerCase](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) - [split](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) - [replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) - [slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) - [substring](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/substring) - [substr](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr) - [concat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat) #### chain.value() Return the string value from the chain ```javascript s(" foo ").trim().capitalize().value(); // => "Foo" ``` When calling a method which does not return a string the resulting value is immediately returned ```javascript s(" foobar ").trim().startsWith("foo"); // => true ``` #### chain.tap(function) => chain Tap into the chain with a custom function ```javascript s("foo").tap(function(value){ return value + "bar"; }).value(); // => "foobar" ``` #### Aliases ```javascript strip = trim lstrip = ltrim rstrip = rtrim center = lrpad rjust = lpad ljust = rpad contains = include q = quote toBool = toBoolean camelcase = camelize ``` ## Maintainers ## This library is maintained by - Esa-Matti Suuronen – ***[@epeli](https://github.com/epeli)*** - Christoph Hermann – ***[@stoeffel](https://github.com/stoeffel)*** ## Licence ## The MIT License Copyright (c) 2011 Esa-Matti Suuronen esa-matti@suuronen.org 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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. [d]: http://www.diveintojavascript.com/core-javascript-reference/the-string-object |