Gathering detailed insights and metrics for underscore.string
Gathering detailed insights and metrics for underscore.string
Gathering detailed insights and metrics for underscore.string
Gathering detailed insights and metrics for underscore.string
@types/underscore.string
TypeScript definitions for underscore.string
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
underscore.string.cli
Use underscore.string on your commandline
handlebars-helper-slugify
{{slugify}} handlebars helper. Uses the awesome underscore.string to transform text into a URL slug. Replaces whitespaces, accentuated and special characters with a dash.
npm install underscore.string
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
3,369 Stars
706 Commits
374 Forks
78 Watching
20 Branches
92 Contributors
Updated on 22 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-8.3%
378,169
Compared to previous day
Last week
0.8%
2,330,952
Compared to previous week
Last month
19.5%
9,278,752
Compared to previous month
Last year
-1%
99,079,546
Compared to previous year
2
The stable release documentation can be found here https://epeli.github.io/underscore.string/
Javascript lacks complete string manipulation operations. This is an attempt to fill that gap. List of build-in methods can be found for example from Dive Into JavaScript. Originally started as an Underscore.js extension but is a full standalone library nowadays.
Upgrading from 2.x to 3.x? Please read the changelog.
Install from npm
npm install underscore.string
Require individual functions
1var slugify = require("underscore.string/slugify"); 2 3slugify("Hello world!"); 4// => hello-world
or load the full library to enable chaining
1var s = require("underscore.string"); 2 3s(" epeli ").trim().capitalize().value(); 4// => "Epeli"
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.
From your Meteor project folder
1 meteor add underscorestring:underscore.string
and you'll be able to access the library with the s global from both the server and the client.
1s.slugify("Hello world!"); 2// => hello-world 3 4s(" epeli ").trim().capitalize().value(); 5// => "Epeli"
The dist/underscore.string.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.
It is still possible use as Underscore.js/Lo-Dash extension
1_.mixin(s.exports());
But it's not recommended since include
, contains
, reverse
and join
are dropped because they collide with the functions already defined by Underscore.js.
If you want to use underscore.string with ramdajs or Lo-Dash-FP you can use underscore.string.fp.
npm install underscore.string.fp
1var S = require('underscore.string.fp'); 2var filter = require('lodash-fp').filter; 3var filter = require('ramda').filter; 4 5filter(S.startsWith('.'), [ 6 '.vimrc', 7 'foo.md', 8 '.zshrc' 9]); 10// => ['.vimrc', '.zshrc']
Formats the numbers.
1numberFormat(1000, 2); 2// => "1,000.00" 3 4numberFormat(123456789.123, 5, ".", ","); 5// => "123,456,789.12300"
Calculates [Levenshtein distance][ld] between two strings. [ld]: http://en.wikipedia.org/wiki/Levenshtein_distance
1levenshtein("kitten", "kittah"); 2// => 2
Converts first letter of the string to uppercase. If true
is passed as second argument the rest
of the string will be converted to lower case.
1capitalize("foo Bar"); 2// => "Foo Bar" 3 4capitalize("FOO Bar", true); 5// => "Foo bar"
Converts first letter of the string to lowercase.
1decapitalize("Foo Bar"); 2// => "foo Bar"
1chop("whitespace", 3); 2// => ["whi", "tes", "pac", "e"]
Trim and replace multiple spaces with a single space.
1clean(" foo bar "); 2// => "foo bar"
Replace diacritic characters with closest ASCII equivalents. Check the source for supported characters. Pull requests welcome for missing characters!
1cleanDiacritics("ääkkönen"); 2// => "aakkonen"
1chars("Hello"); 2// => ["H", "e", "l", "l", "o"]
Returns a copy of the string in which all the case-based characters have had their case swapped.
1swapCase("hELLO"); 2// => "Hello"
Tests if string contains a substring.
1include("foobar", "ob"); 2// => true
Returns number of occurrences of substring in string.
1count("Hello world", "l"); 2// => 3
Converts HTML special characters to their entity equivalents. This function supports cent, yen, euro, pound, lt, gt, copy, reg, quote, amp, apos.
1escapeHTML("<div>Blah blah blah</div>"); 2// => "<div>Blah blah blah</div>"
Converts entity characters to HTML equivalents. This function supports cent, yen, euro, pound, lt, gt, copy, reg, quote, amp, apos, nbsp.
1unescapeHTML("<div>Blah blah blah</div>"); 2// => "<div>Blah blah blah</div>"
1insert("Hellworld", 4, "o "); 2// => "Hello world"
1replaceAll("foo", "o", "a"); 2// => "faa"
1isBlank(""); // => true 2isBlank("\n"); // => true 3isBlank(" "); // => true 4isBlank("a"); // => false
Joins strings together with given separator
1join(" ", "foo", "bar"); 2// => "foo bar"
Split lines to an array
1lines("Hello\nWorld"); 2// => ["Hello", "World"]
Splits a line str
(default '') into several lines of size options.width
(default 75) using a options.seperator
(default '\n'). If options.trailingSpaces
is true, make each line at least width
long using trailing spaces. If options.cut
is true, create new lines in the middle of words. If options.preserveSpaces
is true, preserve the space that should be there at the end of a line (only works if options.cut is false).
1wrap("Hello World", { width:5 }) 2// => "Hello\nWorld" 3 4wrap("Hello World", { width:6, seperator:'.', trailingSpaces: true }) 5// => "Hello .World " 6 7wrap("Hello World", { width:5, seperator:'.', cut:true, trailingSpaces: true }) 8// => "Hello. Worl.d " 9 10wrap("Hello World", { width:5, seperator:'.', preserveSpaces: true }) 11// => "Hello .World" 12
Dedent unnecessary indentation or dedent by a pattern.
Credits go to @sindresorhus. This implementation is similar to https://github.com/sindresorhus/strip-indent
1dedent(" Hello\n World"); 2// => "Hello\n World" 3 4dedent("\t\tHello\n\t\t\t\tWorld"); 5// => "Hello\n\t\tWorld" 6 7dedent(" Hello\n World", " "); // Dedent by 2 spaces 8// => " Hello\n World"
Return reversed string:
1reverse("foobar"); 2// => "raboof"
Like an array splice.
1splice("https://edtsech@bitbucket.org/edtsech/underscore.strings", 30, 7, "epeli"); 2// => "https://edtsech@bitbucket.org/epeli/underscore.strings"
This method checks whether the string begins with starts
at position
(default: 0).
1startsWith("image.gif", "image"); 2// => true 3 4startsWith(".vimrc", "vim", 1); 5// => true
This method checks whether the string ends with ends
at position
(default: string.length).
1endsWith("image.gif", "gif"); 2// => true 3 4endsWith("image.old.gif", "old", 9); 5// => true
Returns the predecessor to str.
1pred("b"); 2// => "a" 3 4pred("B"); 5// => "A"
Returns the successor to str.
1succ("a"); 2// => "b" 3 4succ("A"); 5// => "B"
1titleize("my name is epeli"); 2// => "My Name Is Epeli"
Converts underscored or dasherized string to a camelized one. Begins with a lower case letter unless it starts with an underscore, dash or an upper case letter.
1camelize("moz-transform"); 2// => "mozTransform" 3 4camelize("-moz-transform"); 5// => "MozTransform" 6 7camelize("_moz_transform"); 8// => "MozTransform" 9 10camelize("Moz-transform"); 11// => "MozTransform" 12 13camelize("-moz-transform", true); 14// => "mozTransform"
Converts string to camelized class name. First letter is always upper case
1classify("some_class_name"); 2// => "SomeClassName"
Converts a camelized or dasherized string into an underscored one
1underscored("MozTransform"); 2// => "moz_transform"
Converts a underscored or camelized string into an dasherized one
1dasherize("MozTransform"); 2// => "-moz-transform"
Converts an underscored, camelized, or dasherized string into a humanized one. Also removes beginning and ending whitespace, and removes the postfix '_id'.
1humanize(" capitalize dash-CamelCase_underscore trim "); 2// => "Capitalize dash camel case underscore trim"
Trims defined characters from begining and ending of the string. Defaults to whitespace characters.
1trim(" foobar "); 2// => "foobar" 3 4trim("_-foobar-_", "_-"); 5// => "foobar"
Left trim. Similar to trim, but only for left side.
Right trim. Similar to trim, but only for right side.
1truncate("Hello world", 5); 2// => "Hello..." 3 4truncate("Hello", 10); 5// => "Hello"
Elegant version of truncate. Makes sure the pruned string does not exceed the original length. Avoid half-chopped words when truncating.
1prune("Hello, world", 5); 2// => "Hello..." 3 4prune("Hello, world", 8); 5// => "Hello..." 6 7prune("Hello, world", 5, " (read a lot more)"); 8// => "Hello, world" (as adding "(read a lot more)" would be longer than the original string) 9 10prune("Hello, cruel world", 15); 11// => "Hello, cruel..." 12 13prune("Hello", 10); 14// => "Hello"
Split string by delimiter (String or RegExp), /\s+/ by default.
1words(" I love you "); 2// => ["I", "love", "you"] 3 4words("I_love_you", "_"); 5// => ["I", "love", "you"] 6 7words("I-love-you", /-/); 8// => ["I", "love", "you"] 9 10words(" ") 11// => []
C like string formatting. Makes use of the sprintf-js package.
This function will be removed in the next major release, use the sprintf-js package instead.
1sprintf("%.1f", 1.17); 2// => "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.
1pad("1", 8); 2// => " 1" 3 4pad("1", 8, "0"); 5// => "00000001" 6 7pad("1", 8, "0", "right"); 8// => "10000000" 9 10pad("1", 8, "0", "both"); 11// => "00001000" 12 13pad("1", 8, "bleepblorp", "both"); 14// => "bbbb1bbb"
left-pad a string. Alias for pad(str, length, padStr, "left")
1lpad("1", 8, "0"); 2// => "00000001"
right-pad a string. Alias for pad(str, length, padStr, "right")
1rpad("1", 8, "0"); 2// => "10000000"
left/right-pad a string. Alias for pad(str, length, padStr, "both")
1lrpad("1", 8, '0'); 2// => "00001000"
Parse string to number. Returns NaN if string can't be parsed to number.
1toNumber("2.556"); 2// => 3 3 4toNumber("2.556", 1); 5// => 2.6 6 7toNumber("999.999", -1); 8// => 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.
1strRight("This_is_a_test_string", "_"); 2// => "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.
1strRightBack("This_is_a_test_string", "_"); 2// => "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.
1strLeft("This_is_a_test_string", "_"); 2// => "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.
1strLeftBack("This_is_a_test_string", "_"); 2// => "This_is_a_test";
Removes all html tags from string.
1stripTags("a <a href=\"#\">link</a>"); 2// => "a link" 3 4stripTags("a <a href=\"#\">link</a><script>alert(\"hello world!\")</script>"); 5// => "a linkalert("hello world!")"
Join an array into a human readable sentence.
1toSentence(["jQuery", "Mootools", "Prototype"]); 2// => "jQuery, Mootools and Prototype"; 3 4toSentence(["jQuery", "Mootools", "Prototype"], ", ", " unt "); 5// => "jQuery, Mootools unt Prototype";
The same as toSentence
, but adjusts delimeters to use Serial comma.
1toSentenceSerial(["jQuery", "Mootools"]); 2// => "jQuery and Mootools" 3 4toSentenceSerial(["jQuery", "Mootools", "Prototype"]); 5// => "jQuery, Mootools, and Prototype" 6 7toSentenceSerial(["jQuery", "Mootools", "Prototype"], ", ", " unt "); 8// => "jQuery, Mootools, unt Prototype"
Repeats a string count times.
1repeat("foo", 3); 2// => "foofoofoo" 3 4repeat("foo", 3, "bar"); 5// => "foobarfoobarfoo"
Surround a string with another string.
1surround("foo", "ab"); 2// => "abfooab"
Quotes a string. quoteChar
defaults to "
.
1quote("foo", '"'); 2// => '"foo"';
Unquotes a string. quoteChar
defaults to "
.
1unquote('"foo"'); 2// => "foo" 3 4unquote("'foo'", "'"); 5// => "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
.
1slugify("Un éléphant à l\'orée du bois"); 2// => "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
.
1["foo20", "foo5"].sort(naturalCmp); 2// => ["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.
1toBoolean("true"); 2// => true 3 4toBoolean("FALSE"); 5// => false 6 7toBoolean("random"); 8// => undefined
It can be customized by giving arrays of truth and falsy value matcher as parameters. Matchers can be also RegExp objects.
1toBoolean("truthy", ["truthy"], ["falsy"]); 2// => true 3 4toBoolean("true only at start", [/^true/]); 5// => true
Creates a new string with the results of calling a provided function on every character of the given string.
1map("Hello world", function(x) { 2 return x; 3}); 4// => "Hello world" 5 6map(12345, function(x) { 7 return x; 8}); 9// => "12345" 10 11map("Hello world", function(x) { 12 if (x === 'o') x = 'O'; 13 return x; 14}); 15// => "HellO wOrld"
If you require the full library you can use chaining and aliases
Start a chain. Returns an immutable chain object with the string functions as methods which return a new chain object instead of the plain string value.
The chain object includes also following native Javascript string methods:
Return the string value from the chain
1s(" foo ").trim().capitalize().value(); 2// => "Foo"
When calling a method which does not return a string the resulting value is immediately returned
1s(" foobar ").trim().startsWith("foo"); 2// => true
Tap into the chain with a custom function
1s("foo").tap(function(value){ 2 return value + "bar"; 3}).value(); 4// => "foobar"
1strip = trim 2lstrip = ltrim 3rstrip = rtrim 4center = lrpad 5rjust = lpad 6ljust = rpad 7contains = include 8q = quote 9toBool = toBoolean 10camelcase = camelize
This library is maintained by
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.
The latest stable version of the package.
Stable Version
1
0/10
Summary
Regular Expression Denial of Service in underscore.string
Affected Versions
< 3.3.5
Patched Versions
3.3.5
Reason
no binaries found in the repo
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
Found 2/28 approved changesets -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
license file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
12 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More