Underscore.string Build Status

Javascript lacks complete string manipulation operations. This an attempt to fill that gap. List of build-in methods can be found for example from Dive Into JavaScript.

As name states this an extension for Underscore.js (and Lo-Dash), but it can be used independently from _s-global variable. But with Underscore.js you can use Object-Oriented style and chaining:

  1. _(" epeli ").chain().trim().capitalize().value()
  2. => "Epeli"

Download

Node.js installation

npm package

  1. npm install underscore.string

Standalone usage:

  1. var _s = require('underscore.string');

Integrate with Underscore.js:

  1. var _ = require('underscore');
  2. // Import Underscore.string to separate object, because there are conflict functions (include, reverse, contains)
  3. _.str = require('underscore.string');
  4. // Mix in non-conflict functions to Underscore namespace if you want
  5. _.mixin(_.str.exports());
  6. // All functions, include conflict, will be available through _.str object
  7. _.str.include('Underscore.string', 'string'); // => true

Or Integrate with Underscore.js without module loading

Run the following expression after Underscore.js and Underscore.string are loaded

  1. // _.str becomes a global variable if no module loading is detected
  2. // Mix in non-conflict functions to Underscore namespace
  3. _.mixin(_.str.exports());

String Functions

For availability of functions in this way you need to mix in Underscore.string functions:

  1. _.mixin(_.string.exports());

otherwise functions from examples will be available through .string or .str objects:

  1. _.str.capitalize('epeli')
  2. => "Epeli"

numberFormat _.numberFormat(number, [ decimals=0, decimalSeparator=’.’, orderSeparator=’,’])

Formats the numbers.

  1. _.numberFormat(1000, 2)
  2. => "1,000.00"
  3. _.numberFormat(123456789.123, 5, '.', ',')
  4. => "123,456,789.12300"

levenshtein _.levenshtein(string1, string2)

Calculates Levenshtein distance between two strings.

  1. _.levenshtein('kitten', 'kittah')
  2. => 2

capitalize _.capitalize(string)

Converts first letter of the string to uppercase.

  1. _.capitalize("foo Bar")
  2. => "Foo Bar"

chop _.chop(string, step)

  1. _.chop('whitespace', 3)
  2. => ['whi','tes','pac','e']

clean _.clean(str)

Compress some whitespaces to one.

  1. _.clean(" foo bar ")
  2. => 'foo bar'

chars _.chars(str)

  1. _.chars('Hello')
  2. => ['H','e','l','l','o']

swapCase _.swapCase(str)

Returns a copy of the string in which all the case-based characters have had their case swapped.

  1. _.swapCase('hELLO')
  2. => 'Hello'

include available only through _.str object, because Underscore has function with the same name.

  1. _.str.include("foobar", "ob")
  2. => true

(removed) includes _.includes(string, substring)

Tests if string contains a substring.

  1. _.includes("foobar", "ob")
  2. => true

includes function was removed

But you can create it in this way, for compatibility with previous versions:

  1. _.includes = _.str.include

count _.count(string, substring)

  1. _('Hello world').count('l')
  2. => 3

escapeHTML _.escapeHTML(string)

Converts HTML special characters to their entity equivalents.

  1. _('<div>Blah blah blah</div>').escapeHTML();
  2. => '&lt;div&gt;Blah blah blah&lt;/div&gt;'

unescapeHTML _.unescapeHTML(string)

Converts entity characters to HTML equivalents.

  1. _('&lt;div&gt;Blah blah blah&lt;/div&gt;').unescapeHTML();
  2. => '<div>Blah blah blah</div>'

insert _.insert(string, index, substing)

  1. _('Hello ').insert(6, 'world')
  2. => 'Hello world'

isBlank _.isBlank(string)

  1. _('').isBlank(); // => true
  2. _('\n').isBlank(); // => true
  3. _(' ').isBlank(); // => true
  4. _('a').isBlank(); // => false

join _.join(separator, *strings)

Joins strings together with given separator

  1. _.join(" ", "foo", "bar")
  2. => "foo bar"

lines _.lines(str)

  1. _.lines("Hello\nWorld")
  2. => ["Hello", "World"]

reverse available only through _.str object, because Underscore has function with the same name.

Return reversed string:

  1. _.str.reverse("foobar")
  2. => 'raboof'

splice _.splice(string, index, howmany, substring)

Like a array splice.

  1. _('https://edtsech@bitbucket.org/edtsech/underscore.strings').splice(30, 7, 'epeli')
  2. => 'https://edtsech@bitbucket.org/epeli/underscore.strings'

startsWith _.startsWith(string, starts)

This method checks whether string starts with starts.

  1. _("image.gif").startsWith("image")
  2. => true

endsWith _.endsWith(string, ends)

This method checks whether string ends with ends.

  1. _("image.gif").endsWith("gif")
  2. => true

succ _.succ(str)

Returns the successor to str.

  1. _('a').succ()
  2. => 'b'
  3. _('A').succ()
  4. => 'B'

supplant

Supplant function was removed, use Underscore.js template function.

strip alias for trim

lstrip alias for ltrim

rstrip alias for rtrim

titleize _.titleize(string)

  1. _('my name is epeli').titleize()
  2. => 'My Name Is Epeli'

camelize _.camelize(string)

Converts underscored or dasherized string to a camelized one. Begins with a lower case letter unless it starts with an underscore or string

  1. _('moz-transform').camelize()
  2. => 'mozTransform'
  3. _('-moz-transform').camelize()
  4. => 'MozTransform'

classify _.classify(string)

Converts string to camelized class name. First letter is always upper case

  1. _('some_class_name').classify()
  2. => 'SomeClassName'

underscored _.underscored(string)

Converts a camelized or dasherized string into an underscored one

  1. _('MozTransform').underscored()
  2. => 'moz_transform'

dasherize _.dasherize(string)

Converts a underscored or camelized string into an dasherized one

  1. _('MozTransform').dasherize()
  2. => '-moz-transform'

humanize _.humanize(string)

Converts an underscored, camelized, or dasherized string into a humanized one. Also removes beginning and ending whitespace, and removes the postfix ‘_id’.

  1. _(' capitalize dash-CamelCase_underscore trim ').humanize()
  2. => 'Capitalize dash camel case underscore trim'

trim _.trim(string, [characters])

trims defined characters from begining and ending of the string. Defaults to whitespace characters.

  1. _.trim(" foobar ")
  2. => "foobar"
  3. _.trim("_-foobar-_", "_-")
  4. => "foobar"

ltrim _.ltrim(string, [characters])

Left trim. Similar to trim, but only for left side.

rtrim _.rtrim(string, [characters])

Right trim. Similar to trim, but only for right side.

truncate _.truncate(string, length, truncateString)

  1. _('Hello world').truncate(5)
  2. => 'Hello...'
  3. _('Hello').truncate(10)
  4. => 'Hello'

prune _.prune(string, length, pruneString)

Elegant version of truncate. Makes sure the pruned string does not exceed the original length. Avoid half-chopped words when truncating.

  1. _('Hello, world').prune(5)
  2. => 'Hello...'
  3. _('Hello, world').prune(8)
  4. => 'Hello...'
  5. _('Hello, world').prune(5, ' (read a lot more)')
  6. => 'Hello, world' (as adding "(read a lot more)" would be longer than the original string)
  7. _('Hello, cruel world').prune(15)
  8. => 'Hello, cruel...'
  9. _('Hello').prune(10)
  10. => 'Hello'

words _.words(str, delimiter=/\s+/)

Split string by delimiter (String or RegExp), /\s+/ by default.

  1. _.words(" I love you ")
  2. => ["I","love","you"]
  3. _.words("I_love_you", "_")
  4. => ["I","love","you"]
  5. _.words("I-love-you", /-/)
  6. => ["I","love","you"]
  7. _.words(" ")
  8. => []

sprintf _.sprintf(string format, *arguments)

C like string formatting. Credits goes to Alexandru Marasteanu. For more detailed documentation, see the original page.

  1. _.sprintf("%.1f", 1.17)
  2. "1.2"

pad _.pad(str, length, [padStr, type])

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.

  1. _.pad("1", 8)
  2. -> " 1";
  3. _.pad("1", 8, '0')
  4. -> "00000001";
  5. _.pad("1", 8, '0', 'right')
  6. -> "10000000";
  7. _.pad("1", 8, '0', 'both')
  8. -> "00001000";
  9. _.pad("1", 8, 'bleepblorp', 'both')
  10. -> "bbbb1bbb";

lpad _.lpad(str, length, [padStr])

left-pad a string. Alias for pad(str, length, padStr, 'left')

  1. _.lpad("1", 8, '0')
  2. -> "00000001";

rpad _.rpad(str, length, [padStr])

right-pad a string. Alias for pad(str, length, padStr, 'right')

  1. _.rpad("1", 8, '0')
  2. -> "10000000";

lrpad _.lrpad(str, length, [padStr])

left/right-pad a string. Alias for pad(str, length, padStr, 'both')

  1. _.lrpad("1", 8, '0')
  2. -> "00001000";

center alias for lrpad

ljust alias for rpad

rjust alias for lpad

toNumber _.toNumber(string, [decimals])

Parse string to number. Returns NaN if string can’t be parsed to number.

  1. _('2.556').toNumber()
  2. => 3
  3. _('2.556').toNumber(1)
  4. => 2.6

strRight _.strRight(string, pattern)

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.

  1. _('This_is_a_test_string').strRight('_')
  2. => "is_a_test_string";

strRightBack _.strRightBack(string, pattern)

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.

  1. _('This_is_a_test_string').strRightBack('_')
  2. => "string";

strLeft _.strLeft(string, pattern)

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.

  1. _('This_is_a_test_string').strLeft('_')
  2. => "This";

strLeftBack _.strLeftBack(string, pattern)

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.

  1. _('This_is_a_test_string').strLeftBack('_')
  2. => "This_is_a_test";

stripTags

Removes all html tags from string.

  1. _('a <a href="#">link</a>').stripTags()
  2. => 'a link'
  3. _('a <a href="#">link</a><script>alert("hello world!")</script>').stripTags()
  4. => 'a linkalert("hello world!")'

toSentence _.toSentence(array, [delimiter, lastDelimiter])

Join an array into a human readable sentence.

  1. _.toSentence(['jQuery', 'Mootools', 'Prototype'])
  2. => 'jQuery, Mootools and Prototype';
  3. _.toSentence(['jQuery', 'Mootools', 'Prototype'], ', ', ' unt ')
  4. => 'jQuery, Mootools unt Prototype';

toSentenceSerial _.toSentenceSerial(array, [delimiter, lastDelimiter])

The same as toSentence, but adjusts delimeters to use Serial comma.

  1. _.toSentenceSerial(['jQuery', 'Mootools'])
  2. => 'jQuery and Mootools';
  3. _.toSentenceSerial(['jQuery', 'Mootools', 'Prototype'])
  4. => 'jQuery, Mootools, and Prototype'
  5. _.toSentenceSerial(['jQuery', 'Mootools', 'Prototype'], ', ', ' unt ');
  6. => 'jQuery, Mootools, unt Prototype';

repeat _.repeat(string, count, [separator])

Repeats a string count times.

  1. _.repeat("foo", 3)
  2. => 'foofoofoo';
  3. _.repeat("foo", 3, "bar")
  4. => 'foobarfoobarfoo'

surround _.surround(string, wrap)

Surround a string with another string.

  1. _.surround("foo", "ab")
  2. => 'abfooab';

quote .quote(string, quoteChar) or .q(string, quoteChar)

Quotes a string. quoteChar defaults to ".

  1. _.quote('foo', quoteChar)
  2. => '"foo"';

unquote _.unquote(string, quoteChar)

Unquotes a string. quoteChar defaults to ".

  1. _.unquote('"foo"')
  2. => 'foo';
  3. _.unquote("'foo'", "'")
  4. => 'foo';

slugify _.slugify(string)

Transform text into a URL slug. Replaces whitespaces, accentuated, and special characters with a dash.

  1. _.slugify("Un éléphant à l'orée du bois")
  2. => 'un-elephant-a-loree-du-bois';

Caution: this function is charset dependent

naturalCmp array.sort(_.naturalCmp)

Naturally sort strings like humans would do.

  1. ['foo20', 'foo5'].sort(_.naturalCmp)
  2. => [ 'foo5', 'foo20' ]

toBoolean .toBoolean(string) or .toBool(string)

Turn strings that can be commonly considered as booleas to real booleans. Such as “true”, “false”, “1” and “0”. This function is case insensitive.

  1. _.toBoolean("true")
  2. => true
  3. _.toBoolean("FALSE")
  4. => false
  5. _.toBoolean("random")
  6. => undefined

It can be customized by giving arrays of truth and falsy value matcher as parameters. Matchers can be also RegExp objects.

  1. _.toBoolean("truthy", ["truthy"], ["falsy"])
  2. => true
  3. _.toBoolean("true only at start", [/^true/])
  4. => true

Roadmap

Any suggestions or bug reports are welcome. Just email me or more preferably open an issue.

Problems

We lose two things for include and reverse methods from _.string:

  • Calls like _('foobar').include('bar') aren’t available;
  • Chaining isn’t available too.

But if you need this functionality you can create aliases for conflict functions which will be convenient for you:

  1. _.mixin({
  2. includeString: _.str.include,
  3. reverseString: _.str.reverse
  4. })
  5. // Now wrapper calls and chaining are available.
  6. _('foobar').chain().reverseString().includeString('rab').value()

Standalone Usage

If you are using Underscore.string without Underscore. You also have _.string namespace for it and _.str alias But of course you can just reassign _ variable with _.string

  1. _ = _.string

Changelog

2.4.0

  • Move from rake to gulp
  • Add support form classify camelcase strings
  • Fix bower.json
  • Full changelog

2.3.3

  • Add toBoolean
  • Add unquote
  • Add quote char option to quote
  • Support dash-separated words in titleize
  • Full changelog

2.3.2

  • Add naturalCmp
  • Bug fix to camelize
  • Add ă, ș, ț and ś to slugify
  • Doc updates
  • Add support for component
  • Full changelog

2.3.1

  • Bug fixes to escapeHTML, classify, substr
  • Faster count
  • Documentation fixes
  • Full changelog

2.3.0

  • Added numberformat method
  • Added levenshtein method (Levenshtein distance calculation)
  • Added swapCase method
  • Changed default behavior of words method
  • Added toSentenceSerial method
  • Added surround and quote methods

2.2.1

  • Same as 2.2.0 (2.2.0rc on npm) to fix some npm drama

2.2.0

  • Capitalize method behavior changed
  • Various perfomance tweaks

2.1.1

  • Fixed words method bug
  • Added classify method

2.1.0

  • AMD support
  • Added toSentence method
  • Added slugify method
  • Lots of speed optimizations

2.0.0

  • Added prune, humanize functions
  • Added .string (.str) namespace for Underscore.string library
  • Removed includes function

For upgrading to this version you need to mix in Underscore.string library to Underscore object:

  1. _.mixin(_.string.exports());

and all non-conflict Underscore.string functions will be available through Underscore object. Also function includes has been removed, you should replace this function by _.str.include or create alias _.includes = _.str.include and all your code will work fine.

1.1.6

  • Fixed reverse and truncate
  • Added isBlank, stripTags, inlude(alias for includes)
  • Added uglifier compression

1.1.5

  • Added strRight, strRightBack, strLeft, strLeftBack

1.1.4

  • Added pad, lpad, rpad, lrpad methods and aliases center, ljust, rjust
  • Integration with Underscore 1.1.6

1.1.3

  • Added methods: underscored, camelize, dasherize
  • Support newer version of npm

1.1.2

  • Created functions: lines, chars, words functions

1.0.2

  • Created integration test suite with underscore.js 1.1.4 (now it’s absolutely compatible)
  • Removed ‘reverse’ function, because this function override underscore.js ‘reverse’

Contribute

  • Fork & pull request. Don’t forget about tests.
  • If you planning add some feature please create issue before.

Otherwise changes will be rejected.

Contributors list

Can be found here.

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.