Underscore.string.fp
This is a wrapper for underscore.string to use it as a FP-library or with a library like lodash-fp or Ramda
Usage
In Node.js and Browserify
Install from npm
npm install underscore.string.fp
Require individual functions
var include = require("underscore.string.fp/include");
var includeHello = include('Hello');
includeHello("Hello world!");
includeHello("Nope");
or load the full library to compose functions
var rockit = S(
S.titleize(),
S.insert('rocks', 9),
S.trim('_')
);
rockit("__stoeffel !__");
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.
Others
The dist/underscore.string.fp.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.
Ramda integration
You can use it with ramda.
R.map(S.camelize(), [
'Moo boo',
'Foo bar'
]);
R.filter(S.startsWith('.'), [
'.vimrc',
'foo.md',
'.zshrc'
]);
lodash-fp integration
You can use it with lodash-fp.
_.map(S.camelize(), [
'Moo boo',
'Foo bar'
]);
_.filter(S.startsWith('.'), [
'.vimrc',
'foo.md',
'.zshrc'
]);
Download
API
Individual functions
numberFormat(number) => string
Formats the numbers.
numberFormat(1000);
numberFormatDecimal(decimals, number) => string
Formats the numbers.
numberFormatDecimal(2)(1000);
numberFormatSeparator(decimalSeparator, orderSeparator, decimal, number) => string
Formats the numbers.
numberFormatSeparator(".", "'", 5, 123456789.123);
levenshtein(string1, string2) => number
Calculates [Levenshtein distance][ld] between two strings.
[ld]: http://en.wikipedia.org/wiki/Levenshtein_distance
levenshtein("kitten")("kittah");
capitalize(string) => string
Converts first letter of the string to uppercase.
capitalize()("foo Bar");
capitalize("foo Bar");
decapitalize(string) => string
Converts first letter of the string to lowercase.
decapitalize()("Foo Bar");
decapitalize("Foo Bar");
chop(step, string) => array
chop(3)("whitespace");
clean(string) => string
Trim and replace multiple spaces with a single space.
clean()(" foo bar ");
clean(" foo bar ");
chars()("Hello");
chars("Hello");
swapCase(string) => string
Returns a copy of the string in which all the case-based characters have had their case swapped.
swapCase()("hELLO");
swapCase("hELLO");
include(substring, string) => boolean
Tests if string contains a substring.
include("ob")("foobar");
count(substring, string) => number
count("l")("Hello world");
escapeHTML(string) => string
Converts HTML special characters to their entity equivalents.
escapeHTML()("<div>Blah blah blah</div>");
escapeHTML("<div>Blah blah blah</div>");
unescapeHTML(string) => string
Converts entity characters to HTML equivalents.
unescapeHTML()("<div>Blah blah blah</div>");
unescapeHTML("<div>Blah blah blah</div>");
insert(substring, index, string) => string
insert("world", 6)("Hello ");
replaceAll(replace, find, string) => string
replaceAll("a")("o")("foo");
replaceAllIgnoreCase(replace, find, string) => string
replaceAll("a")("o")("fOo");
isBlank(string) => boolean
isBlank("");
isBlank("\n");
isBlank(" ");
isBlank("a");
join(separator, strings) => string
Joins strings together with given separator
join(" ")(["foo", "bar"]);
lines(str) => array
Split lines to an array
lines()("Hello\nWorld");
lines("Hello\nWorld");
dedent(str) => string
Dedent unnecessary indentation
Credits go to @sindresorhus.
This implementation is similar to https://github.com/sindresorhus/strip-indent
dedent()(" Hello\n World");
dedent("\t\tHello\n\t\t\t\tWorld");
dedentPattern(pattern, str) => string
Dedent by a pattern.
dedentPattern(" ")(" Hello\n World");
reverse(string) => string
Return reversed string:
reverse()("foobar");
reverse("foobar");
splice(substring, howmany, index, string) => string
Like an array splice.
splice("epeli")(7)(30)("https://edtsech@bitbucket.org/edtsech/underscore.strings");
startsWith(starts, string) => boolean
This method checks whether the string begins with starts
.
startsWith("image")("image.gif");
startsWithAt(starts, position, string) => boolean
This method checks whether the string begins with starts
at position
.
startsWithAt(1)("vim")(".vimrc");
endsWith(ends, string) => boolean
This method checks whether the string ends with ends
.
endsWith("gif")("image.gif");
endsWithAt(position, ends, string) => boolean
This method checks whether the string ends with ends
at position
.
endsWithAt(9)("old")("image.old.gif");
pred(string) => string
Returns the predecessor to str.
pred()("b");
pred("B");
succ(string) => string
Returns the successor to str.
succ()("a");
succ("A");
titleize(string) => string
titleize()("my name is epeli");
titleize("my name is epeli");
camelize(string) => string
Converts underscored or dasherized string to a camelized one.
camelize("moz-transform");
camelize("-moz-transform");
camelize("_moz_transform");
camelize("Moz-transform");
pascalize(string) => string
Converts underscored or dasherized string to a pascalized one. Begins with
a lower case letter unless it starts with an underscore, dash or an upper case letter.
pascalize("moz-transform");
pascalize("-moz-transform");
pascalize("_moz_transform");
pascalize("Moz-transform");
classify(string) => string
Converts string to camelized class name. First letter is always upper case
classify()("some_class_name");
classify("some_class_name");
underscored(string) => string
Converts a camelized or dasherized string into an underscored one
underscored()("MozTransform");
underscored("MozTransform");
dasherize(string) => string
Converts a underscored or camelized string into an dasherized one
dasherize()("MozTransform");
dasherize("MozTransform");
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'.
humanize()(" capitalize dash-CamelCase_underscore trim ");
humanize(" capitalize dash-CamelCase_underscore trim ");
trim(characters, string) => string
Trims defined characters from begining and ending of the string.
trim(' ')(" foobar ");
trim("_-foobar-_", "_-");
ltrim(characters, string) => string
Left trim. Similar to trim, but only for left side.
rtrim(characters, string) => string
Right trim. Similar to trim, but only for right side.
truncate(truncateString, length, string) => string
truncate('...')(5)("Hello world");
truncate('...')(10)("Hello");
prune(pruneString, length, string) => string
Elegant version of truncate. Makes sure the pruned string does not exceed the
original length. Avoid half-chopped words when truncating.
prune('...')(5)("Hello, world");
prune('...')(8)("Hello, world");
prune(" (read a lot more)")(5)("Hello, world");
prune( '...')(1)("Hello, cruel world");
prune( '...')(1)("Hello");
words(str) => array
Split string by /\s+/.
words()(" I love you ");
words(" ")
wordsDelim(delimiter=/\s+/, str) => array
Split string by delimiter (String or RegExp).
words("_")("I_love_you");
words(/-/)("I-love-you");
sprintf(arguments, string format) => string
C like string formatting.
Credits goes to Alexandru Marasteanu.
For more detailed documentation, see the original page.
sprintf(1.17)("%.1f");
pad(padStr, length, str) => 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.
pad(" ")(8)("1");
pad("0")(8)("1");
lpad(padStr, length, str) => string
left-pad a string. Alias for pad(str, length, padStr, "left")
lpad("0")(8)("1");
rpad(padStr, length, str) => string
right-pad a string. Alias for pad(str, length, padStr, "right")
rpad("0")(8)("1");
lrpad(padStr, length, str) => string
left/right-pad a string. Alias for pad(str, length, padStr, "both")
lrpad('0')(8)("1");
toNumber(decimals, string) => number
Parse string to number. Returns NaN if string can't be parsed to number.
toNumber(0)("2.556");
toNumber(1)("2.556");
toNumber(-1)("999.999");
strRight(pattern, string) => 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.
strRight("_")("This_is_a_test_string");
strRightBack(pattern, string) => 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.
strRightBack("_")("This_is_a_test_string");
strLeft(pattern, string) => 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.
strLeft("_")("This_is_a_test_string");
strLeftBack(pattern, string) => 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.
strLeftBack("_")("This_is_a_test_string");
stripTags(string) => string
Removes all html tags from string.
stripTags()("a <a href="#">link</a>");
stripTags("a <a href="#">link</a><script>alert("hello world!")</script>");
toSentence(lastDelimiter, delimiter, array) => string
Join an array into a human readable sentence.
toSentence(" and ")(", ")((["jQuery", "Mootools", "Prototype"]);
toSentence(" unt ")(", ")((["jQuery", "Mootools", "Prototype"]);
toSentenceSerial(lastDelimiter, delimiter, array) => string
The same as toSentence
, but adjusts delimeters to use Serial comma.
toSentenceSerial(' and ')(', ')(["jQuery", "Mootools"]);
toSentenceSerial(' and ')(', ')(["jQuery", "Mootools", "Prototype"]);
toSentenceSerial(' unt ')(', ')(["jQuery", "Mootools", "Prototype"]);
repeat(separator, count, string) => string
Repeats a string count times.
repeat('')(3)("foo");
repeat("bar")(3)("foo");
surround(wrap, string) => string
Surround a string with another string.
surround("ab")("foo");
quote(quoteChar, string) or q(quoteChar, string) => string
Quotes a string. quoteChar
.
quote('"')("foo");
unquote(quoteChar, string) => string
Unquotes a string. quoteChar
.
unquote('"')('"foo"');
unquote("'")("'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
.
slugify()("Un éléphant à l\'orée du bois");
slugify("Un éléphant à l\'orée 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. Note: this means "a" > "A". Use .toLowerCase
if this isn't to be desired.
Just past it to Array#sort
.
["foo20", "foo5"].sort(naturalCmp);
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.
toBoolean("true");
toBoolean("FALSE");
toBoolean("random");
Library functions
If you require the full library you can use composing and aliases
s(functions) => function
Compose new functions.
var rockit = S(
S.titleize(),
S.insert('rocks', 9),
S.trim('_')
);
rockit("__stoeffel !__");
Aliases
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
Licence
The MIT License
Copyright (c) 2015 Christoph Hermann schtoeffel@gmail.com
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.