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.
Development Version (2.3.0) | 19kb, Uncompressed |
Production Version (2.3.0) | 9kb, Packed and Gzipped |
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
capitalize_.capitalize(string)
Converts first letter of the string to uppercase.
_.capitalize("foo Bar"); => "Foo Bar"
chop_.chop(string, step)
_.chop('whitespace', 3); => ['whi','tes','pac','e']
clean_.clean(str)
Compress some whitespaces to one.
_.clean(" foo bar "); => "foo bar"
chars_.chars(str)
Converts a string into an array of characters
_.chars('Hello'); => ['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.
_.swapCase('hELLO'); => '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
escapeHTML_.escapeHTML(string)
Converts HTML special characters to their entity equivalents.
_.('<div>Blah blah blah</div>').escapeHTML(); => '<div>Blah blah blah</div>'
unescapeHTML_.unescapeHTML(string)
Converts entity characters to HTML equivalents.
_.('<div>Blah blah blah</div>').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'
isBlank_.isBlank(string)
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"
lines_.lines(str)
Splits a string into an array based on the new line (\n) character.
_.lines("Hello\nWorld"); => ["Hello", "World"]
reverse_.reverse(string)
Returns a reversed string.
Available only through _.str object, because Underscore has function with the same name.
_.str.reverse("foobar"); => 'raboof'
splice_.splice(string, index, howmany, substring)
Like an array splice.
_.('https://edtsech@bitbucket.org/edtsech/underscore.strings').splice(30, 7, 'epeli'); => 'https://edtsech@bitbucket.org/epeli/underscore.strings'
startsWith_.startsWith(string, starts)
Checks whether a string starts with another substring.
_.("image.gif").startsWith("image"); => true
endsWith_.endsWith(string, ends)
Checks whether a string ends with another substring.
_.("image.gif").endsWith("gif") => true
succ_.succ(str)
Returns the successor to str.
_.('a').succ(); => 'b' _.('A').succ(); => 'B'
camelize_.camelize(string)
Converts underscored or dasherized string to a camelized one.
_('-moz-transform').camelize(); => 'MozTransform'
classify_.classify(string)
Converts string to camelized class name.
_.('some_class_name').classify(); => 'SomeClassName'
underscored_.underscored(string)
Converts a camelized or dasherized string into an underscored one.
_.('MozTransform').underscored(); => 'moz_transform'
dasherize_.dasherize(string)
Converts a underscored or camelized string into an dasherized one.
_.('MozTransform').dasherize(); => '-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]
intersection_.intersection(*arrays)
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"
center_.center(str, 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.
_.('This_is_a_test_string').strRight('_'); => "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.
_.('This_is_a_test_string').strRightBack('_'); => "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_is_a_test_string').strLeft('_'); => "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_string').strLeftBack('_'); => "This_is_a_test"
stripTags_.stripTags(string)
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 ".
_.unquote('"foo"'); => 'foo' _.unquote("'foo'", "'"); => 'foo'
slugify_.slugify(string)
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'
naturalCmparray.sort(_.naturalCmp)
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
2.3.3 — July 15, 2013 — Diff