This is a wrapper for underscore.string to use it as a FP-library or with a library like lodash-fp or Ramda
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!");
// => true
includeHello("Nope");
// => false
or load the full library to compose functions
var rockit = S(
S.titleize(),
S.insert('rocks', 9),
S.trim('_')
);
// S.titleize(S.insert('rocks', 9, S.trim('_', "__stoeffel !__")));
rockit("__stoeffel !__");
// => "Stoeffel Rocks!"
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.
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.
You can use it with ramda.
R.map(S.camelize(), [
'Moo boo',
'Foo bar'
]);
// => ['mooBoo', 'fooBoo']
R.filter(S.startsWith('.'), [
'.vimrc',
'foo.md',
'.zshrc'
]);
// => ['.vimrc', '.zshrc']
You can use it with lodash-fp.
_.map(S.camelize(), [
'Moo boo',
'Foo bar'
]);
// => ['mooBoo', 'fooBoo']
_.filter(S.startsWith('.'), [
'.vimrc',
'foo.md',
'.zshrc'
]);
// => ['.vimrc', '.zshrc']
- Development version Uncompressed with Comments
- Production version Minified
Formats the numbers.
numberFormat(1000);
// => "1,000"
Formats the numbers.
numberFormatDecimal(2)(1000);
// => "1,000.00"
Formats the numbers.
numberFormatSeparator(".", "'", 5, 123456789.123);
// => "123'456'789.12300"
Calculates [Levenshtein distance][ld] between two strings. [ld]: http://en.wikipedia.org/wiki/Levenshtein_distance
levenshtein("kitten")("kittah");
// => 2
Converts first letter of the string to uppercase.
capitalize()("foo Bar");
// => "Foo Bar"
capitalize("foo Bar");
// => "Foo Bar"
Converts first letter of the string to lowercase.
decapitalize()("Foo Bar");
// => "foo Bar"
decapitalize("Foo Bar");
// => "foo Bar"
chop(3)("whitespace");
// => ["whi", "tes", "pac", "e"]
Trim and replace multiple spaces with a single space.
clean()(" foo bar ");
// => "foo bar"
clean(" foo bar ");
// => "foo bar"
chars()("Hello");
// => ["H", "e", "l", "l", "o"]
chars("Hello");
// => ["H", "e", "l", "l", "o"]
Returns a copy of the string in which all the case-based characters have had their case swapped.
swapCase()("hELLO");
// => "Hello"
swapCase("hELLO");
// => "Hello"
Tests if string contains a substring.
include("ob")("foobar");
// => true
count("l")("Hello world");
// => 3
Converts HTML special characters to their entity equivalents.
escapeHTML()("<div>Blah blah blah</div>");
// => "<div>Blah blah blah</div>"
escapeHTML("<div>Blah blah blah</div>");
// => "<div>Blah blah blah</div>"
Converts entity characters to HTML equivalents.
unescapeHTML()("<div>Blah blah blah</div>");
// => "<div>Blah blah blah</div>"
unescapeHTML("<div>Blah blah blah</div>");
// => "<div>Blah blah blah</div>"
insert("world", 6)("Hello ");
// => "Hello world"
replaceAll("a")("o")("foo");
// => "faa"
replaceAll("a")("o")("fOo");
// => "faa"
isBlank(""); // => true
isBlank("\n"); // => true
isBlank(" "); // => true
isBlank("a"); // => false
Joins strings together with given separator
join(" ")(["foo", "bar"]);
// => "foo bar"
Split lines to an array
lines()("Hello\nWorld");
// => ["Hello", "World"]
lines("Hello\nWorld");
// => ["Hello", "World"]
Dedent unnecessary indentation
Credits go to @sindresorhus. This implementation is similar to https://github.com/sindresorhus/strip-indent
dedent()(" Hello\n World");
// => "Hello\n World"
dedent("\t\tHello\n\t\t\t\tWorld");
// => "Hello\n\t\tWorld"
Dedent by a pattern.
dedentPattern(" ")(" Hello\n World"); // Dedent by 2 spaces
// => " Hello\n World"
Return reversed string:
reverse()("foobar");
// => "raboof"
reverse("foobar");
// => "raboof"
Like an array splice.
splice("epeli")(7)(30)("https://edtsech@bitbucket.org/edtsech/underscore.strings");
// => "https://edtsech@bitbucket.org/epeli/underscore.strings"
This method checks whether the string begins with starts
.
startsWith("image")("image.gif");
// => true
This method checks whether the string begins with starts
at position
.
startsWithAt(1)("vim")(".vimrc");
// => true
This method checks whether the string ends with ends
.
endsWith("gif")("image.gif");
// => true
This method checks whether the string ends with ends
at position
.
endsWithAt(9)("old")("image.old.gif");
// => true
Returns the predecessor to str.
pred()("b");
// => "a"
pred("B");
// => "A"
Returns the successor to str.
succ()("a");
// => "b"
succ("A");
// => "B"
titleize()("my name is epeli");
// => "My Name Is Epeli"
titleize("my name is epeli");
// => "My Name Is Epeli"
Converts underscored or dasherized string to a camelized one.
camelize("moz-transform");
// => "mozTransform"
camelize("-moz-transform");
// => "mozTransform"
camelize("_moz_transform");
// => "mozTransform"
camelize("Moz-transform");
// => "mozTransform"
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");
// => "mozTransform"
pascalize("-moz-transform");
// => "MozTransform"
pascalize("_moz_transform");
// => "MozTransform"
pascalize("Moz-transform");
// => "MozTransform"
Converts string to camelized class name. First letter is always upper case
classify()("some_class_name");
// => "SomeClassName"
classify("some_class_name");
// => "SomeClassName"
Converts a camelized or dasherized string into an underscored one
underscored()("MozTransform");
// => "moz_transform"
underscored("MozTransform");
// => "moz_transform"
Converts a underscored or camelized string into an dasherized one
dasherize()("MozTransform");
// => "-moz-transform"
dasherize("MozTransform");
// => "-moz-transform"
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 ");
// => "Capitalize dash camel case underscore trim"
humanize(" capitalize dash-CamelCase_underscore trim ");
// => "Capitalize dash camel case underscore trim"
Trims defined characters from begining and ending of the string.
trim(' ')(" foobar ");
// => "foobar"
trim("_-foobar-_", "_-");
// => "foobar"
Left trim. Similar to trim, but only for left side.
Right trim. Similar to trim, but only for right side.
truncate('...')(5)("Hello world");
// => "Hello..."
truncate('...')(10)("Hello");
// => "Hello"
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");
// => "Hello..."
prune('...')(8)("Hello, world");
// => "Hello..."
prune(" (read a lot more)")(5)("Hello, world");
// => "Hello, world" (as adding "(read a lot more)" would be longer than the original string)
prune( '...')(1)("Hello, cruel world");
// => "Hello, cruel..."
prune( '...')(1)("Hello");
// => "Hello"
Split string by /\s+/.
words()(" I love you ");
// => ["I", "love", "you"]
words(" ")
// => []
Split string by delimiter (String or RegExp).
words("_")("I_love_you");
// => ["I", "love", "you"]
words(/-/)("I-love-you");
// => ["I", "love", "you"]
C like string formatting. Credits goes to Alexandru Marasteanu. For more detailed documentation, see the original page.
sprintf(1.17)("%.1f");
// => "1.2"
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");
// => " 1"
pad("0")(8)("1");
// => "00000001"
left-pad a string. Alias for pad(str, length, padStr, "left")
lpad("0")(8)("1");
// => "00000001"
right-pad a string. Alias for pad(str, length, padStr, "right")
rpad("0")(8)("1");
// => "10000000"
left/right-pad a string. Alias for pad(str, length, padStr, "both")
lrpad('0')(8)("1");
// => "00001000"
Parse string to number. Returns NaN if string can't be parsed to number.
toNumber(0)("2.556");
// => 3
toNumber(1)("2.556");
// => 2.6
toNumber(-1)("999.999");
// => 990
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");
// => "is_a_test_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");
// => "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");
// => "This";
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");
// => "This_is_a_test";
Removes all html tags from string.
stripTags()("a <a href="#">link</a>");
// => "a link"
stripTags("a <a href="#">link</a><script>alert("hello world!")</script>");
// => "a linkalert("hello world!")"
Join an array into a human readable sentence.
toSentence(" and ")(", ")((["jQuery", "Mootools", "Prototype"]);
// => "jQuery, Mootools and Prototype";
toSentence(" unt ")(", ")((["jQuery", "Mootools", "Prototype"]);
// => "jQuery, Mootools unt Prototype";
The same as toSentence
, but adjusts delimeters to use Serial comma.
toSentenceSerial(' and ')(', ')(["jQuery", "Mootools"]);
// => "jQuery and Mootools"
toSentenceSerial(' and ')(', ')(["jQuery", "Mootools", "Prototype"]);
// => "jQuery, Mootools, and Prototype"
toSentenceSerial(' unt ')(', ')(["jQuery", "Mootools", "Prototype"]);
// => "jQuery, Mootools, unt Prototype"
Repeats a string count times.
repeat('')(3)("foo");
// => "foofoofoo"
repeat("bar")(3)("foo");
// => "foobarfoobarfoo"
Surround a string with another string.
surround("ab")("foo");
// => "abfooab"
Quotes a string. quoteChar
.
quote('"')("foo");
// => '"foo"';
Unquotes a string. quoteChar
.
unquote('"')('"foo"');
// => "foo"
unquote("'")("'foo'");
// => "foo"
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");
// => "un-elephant-a-l-oree-du-bois"
slugify("Un éléphant à l\'orée du bois");
// => "un-elephant-a-l-oree-du-bois"
Caution: this function is charset dependent
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);
// => ["foo5", "foo20"]
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
If you require the full library you can use composing and aliases
Compose new functions.
var rockit = S(
S.titleize(),
S.insert('rocks', 9),
S.trim('_')
);
// S.titleize(S.insert('rocks', 9, S.trim('_', "__stoeffel !__")));
rockit("__stoeffel !__");
// => "Stoeffel Rocks!"
strip = trim
lstrip = ltrim
rstrip = rtrim
center = lrpad
rjust = lpad
ljust = rpad
contains = include
q = quote
toBool = toBoolean
camelcase = camelize
This library is maintained by
- Christoph Hermann – @stoeffel
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.