Fork me on GitHub



Underscore.string is string manipulation extension for JavaScript that you can use with or without Underscore.js

Underscore.string is JavaScript library for comfortable manipulation with strings, extension for Underscore.js inspired by Prototype.js, Right.js, Underscore and beautiful Ruby language.

Underscore.string provides you several useful functions: capitalize, clean, includes, count, escapeHTML, unescapeHTML, insert, splice, startsWith, endsWith, titleize, trim, truncate and so on.

The project is hosted on GitHub. You can report bugs and discuss features on the issues page.

Downloads (Right-click, and use "Save As")

Development Version (2.3.0) 19kb, Uncompressed
Production Version (2.3.0) 9kb, Packed and Gzipped

Strings Functions

numberFormat_.numberFormat(number, [ decimals=0, decimalSeparator='.', orderSeparator=','])
Formats the numbers.

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

levenshtein_.levenshtein(string1, string2)
Calculates Levenshtein distance between two strings.

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

Converts first letter of the string to uppercase.

_.capitalize("foo Bar");
=> "Foo Bar"

chop_.chop(string, step)

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

Compress some whitespaces to one.

_.clean(" foo    bar   ");
=> "foo bar"

Converts a string into an array of characters

=> ['H','e','l','l','o']

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

=> 'Hello'

include_.include(string, substring)
Tests if string contains a substring.

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

includes_.includes(string, substring)
Function was removed but you can create it in this way, for compatibility with previous versions:

_includes = _.str.include

count_.count(string, substring)
Counts the ocurrences of a substring for a given string

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

Converts HTML special characters to their entity equivalents.

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

Converts entity characters to HTML equivalents.

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

insert_.insert(string, index, substing)
Inserts a substring on a the specified index.

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

Tests if a string is empty

_.('').isBlank(); => true
_.('\n').isBlank(); => true
_.(' ').isBlank(); => true
_.('a').isBlank(); => false

join_.join(separator, *strings)
Joins strings together with given separator.

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

Splits a string into an array based on the new line (\n) character.

=> ["Hello", "World"]

Returns a reversed string.
Available only through _.str object, because Underscore has function with the same name.

=> 'raboof'

splice_.splice(string, index, howmany, substring)
Like an array splice.

_.('').splice(30, 7, 'epeli');
=> ''

startsWith_.startsWith(string, starts)
Checks whether a string starts with another substring.

=> true

endsWith_.endsWith(string, ends)
Checks whether a string ends with another substring.

=> true

Returns the successor to str.

_.('a').succ(); => 'b'
_.('A').succ(); => 'B'

Converts underscored or dasherized string to a camelized one.

=> 'MozTransform'

Converts string to camelized class name.

=> 'SomeClassName'

Converts a camelized or dasherized string into an underscored one.

=> 'moz_transform'

Converts a underscored or camelized string into an dasherized one.

=> '-moz-transform'

trim_.trim(string, [characters])
Trims defined characters from begining and ending of the string. Defaults to whitespace characters.

_.trim("  foobar   ") => "foobar"
_.trim("_-foobar-_") => "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)
Truncates a string to the specified number of characters. TruncateString defaults to '...'

_.('Hello world').truncate(5); => 'Hello...'
_.('Hello').truncate(10); => 'Hello'

prune_.prune(string, length, pruneString)
Elegant version of truncate. Makes sure the pruned string does not exceed the original length. Avoids half-chopped words when truncating.

_.('Hello, world').prune(5); => 'Hello...'
_.('Hello, world').prune(8); => 'Hello...'

_.('Hello, world').prune(5, ' (read a lot more)'); => 'Hello, world' (as adding "(read a lot more)" would be longer than the original string)
_.('Hello, cruel world').prune(15); => 'Hello, cruel...'
_.('Hello').prune(10); => 'Hello'

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

_.words("   I   love   you   "); => ["I","love","you"]
_.words("I_love_you", "_"); => ["I","love","you"]
_.words("I-love-you", /-/); => ["I","love","you"]
_.words("    "); => []

without_.without(array, [*values])
Returns a copy of the array with all instances of the values removed.

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
=> [2, 3, 4]

sprintf_.sprintf(string format, *arguments)
C like string formatting. Credits goes to Alexandru Marasteanu. For more detailed documentation, see the original page.

_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]

Computes the list of values that are the intersection of all the arrays. Each value in the result is present in each of the arrays.

_.sprintf("%.1f", 1.17);
=> "1.2"

pad_.pad(string, length, [padStr, type])
Pads a string 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.

_.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_.lpad(str, length, [padStr]) Alias: pad(str, length, padStr, 'left')
Left-pad a string.

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

rpad_.rpad(str, length, [padStr]) Alias: pad(str, length, padStr, 'right')
Right-pad a string.

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

lrpad_.lrpad(str, length, [padStr]) Alias: pad(str, length, padStr, 'both')
Left/Right-pad a string.

_.lrpad("1", 8, '0'); => "00001000", length, [padStr]) Alias: lrpad

ljust_.ljust(str, length, [padStr]) Alias: rpad

rjust_.rjust(str, length, [padStr]) Alias: lpad

toNumber_.toNumber(string, [decimals])
Parse string to number. Returns NaN if string can't be parsed to number.

_.('2.556').toNumber(); => 3
_.('2.556').toNumber(1); => 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.

=> "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.

=> "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.

=> "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.

=> "This_is_a_test"

Removes all html tags from string.

_.('a link').stripTags();
=> 'a link'

_.('a link<script>alert("hello world!")</script>').stripTags();
=> 'a linkalert("hello world!")'

toSentence_.toSentence(array, [delimiter, lastDelimiter])
Join an array into a human readable sentence.

_.toSentence(['jQuery', 'Mootools', 'Prototype']);
=> 'jQuery, Mootools and Prototype'

_.toSentence(['jQuery', 'Mootools', 'Prototype'], ', ', ' unt ');
=> 'jQuery, Mootools unt Prototype'

toSentenceSerial_.toSentenceSerial(array, [delimiter, lastDelimiter])
The same as toSentence, but adjusts delimeters to use Serial comma.

_.toSentenceSerial(['jQuery', 'Mootools']);
=> 'jQuery and Mootools'

_.toSentenceSerial(['jQuery', 'Mootools', 'Prototype']);
=> 'jQuery, Mootools, and Prototype'

_.toSentenceSerial(['jQuery', 'Mootools', 'Prototype'], ', ', ' unt ');
=> 'jQuery, Mootools, unt Prototype'

repeat_.repeat(string, count, [separator])
Repeats a string count times.

_.repeat("foo", 3)
=> 'foofoofoo';

_.repeat("foo", 3, "bar")
=> 'foobarfoobarfoo'

surround_.surround(string, wrap)
Surround a string with another string.

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

quote_.quote(string, quoteChar) or _.q(string, quoteChar)
Quotes a string. quoteChar defaults to ".

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

unquote_.unquote(string, quoteChar)
Unquotes a string. quoteChar defaults to ".

=> 'foo'
_.unquote("'foo'", "'");
=> 'foo'

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

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

Naturally sort strings like humans would do.

['foo20', 'foo5'].sort(_.naturalCmp);
=> [ '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.

_.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.

_.toBoolean("truthy", ["truthy"], ["falsy"]); => true
_.toBoolean("true only at start", [/^true/]); => true

Change Log

2.3.3July 15, 2013Diff