HTML5 Security Cheatsheet for more details.
When working with HTML you should always quote attribute values to reduce XSS vectors.
[string='']
(string): The string to escape.(string): Returns the escaped string.
_.escape('fred, barney, & pebbles');// => 'fred, barney, & pebbles'
_.escapeRegExp([string=''])
Escapes the RegExp
special characters "\", "/", "^", "$", ".", "|", "?", "*", "+", "(", ")", "[", "]", "{" and "}" in string
.
[string='']
(string): The string to escape.(string): Returns the escaped string.
_.escapeRegExp('[lodash](https://lodash.com/)');// => '\[lodash\]\(https:\/\/lodash\.com\/\)'
_.kebabCase([string=''])
Converts string
to kebab case.
[string='']
(string): The string to convert.(string): Returns the kebab cased string.
_.kebabCase('Foo Bar');// => 'foo-bar' _.kebabCase('fooBar');// => 'foo-bar' _.kebabCase('__foo_bar__');// => 'foo-bar'
_.pad([string=''], [length=0], [chars=' '])
Pads string
on the left and right sides if it's shorter than length
. Padding characters are truncated if they can't be evenly divided by length
.
[string='']
(string): The string to pad.[length=0]
(number): The padding length.[chars=' ']
(string): The string used as padding.(string): Returns the padded string.
_.pad('abc', 8);// => ' abc ' _.pad('abc', 8, '_-');// => '_-abc_-_' _.pad('abc', 3);// => 'abc'
_.padLeft([string=''], [length=0], [chars=' '])
Pads string
on the left side if it's shorter than length
. Padding characters are truncated if they exceed length
.
[string='']
(string): The string to pad.[length=0]
(number): The padding length.[chars=' ']
(string): The string used as padding.(string): Returns the padded string.
_.padLeft('abc', 6);// => ' abc' _.padLeft('abc', 6, '_-');// => '_-_abc' _.padLeft('abc', 3);// => 'abc'
_.padRight([string=''], [length=0], [chars=' '])
Pads string
on the right side if it's shorter than length
. Padding characters are truncated if they exceed length
.
[string='']
(string): The string to pad.[length=0]
(number): The padding length.[chars=' ']
(string): The string used as padding.(string): Returns the padded string.
_.padRight('abc', 6);// => 'abc ' _.padRight('abc', 6, '_-');// => 'abc_-_' _.padRight('abc', 3);// => 'abc'
_.parseInt(string, [radix])
Converts string
to an integer of the specified radix. If radix
is undefined
or 0
, a radix
of 10
is used unless value
is a hexadecimal, in which case a radix
of 16
is used.
Note: This method aligns with the ES5 implementation of parseInt
.
string
(string): The string to convert.[radix]
(number): The radix to interpret value
by.(number): Returns the converted integer.
_.parseInt('08');// => 8 _.map(['6', '08', '10'], _.parseInt);// => [6, 8, 10]
_.repeat([string=''], [n=0])
Repeats the given string n
times.
[string='']
(string): The string to repeat.[n=0]
(number): The number of times to repeat the string.(string): Returns the repeated string.
_.repeat('*', 3);// => '***' _.repeat('abc', 2);// => 'abcabc' _.repeat('abc', 0);// => ''
_.snakeCase([string=''])
Converts string
to snake case.
[string='']
(string): The string to convert.(string): Returns the snake cased string.
_.snakeCase('Foo Bar');// => 'foo_bar' _.snakeCase('fooBar');// => 'foo_bar' _.snakeCase('--foo-bar');// => 'foo_bar'
_.startCase([string=''])
Converts string
to start case.
[string='']
(string): The string to convert.(string): Returns the start cased string.
_.startCase('--foo-bar');// => 'Foo Bar' _.startCase('fooBar');// => 'Foo Bar' _.startCase('__foo_bar__');// => 'Foo Bar'
_.startsWith([string=''], [target], [position=0])
Checks if string
starts with the given target string.
[string='']
(string): The string to search.[target]
(string): The string to search for.[position=0]
(number): The position to search from.(boolean): Returns true
if string
starts with target
, else false
.
_.startsWith('abc', 'a');// => true _.startsWith('abc', 'b');// => false _.startsWith('abc', 'b', 1);// => true
_.template([string=''], [options])
Creates a compiled template function that can interpolate data properties in "interpolate" delimiters, HTML-escape interpolated data properties in "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data properties may be accessed as free variables in the template. If a setting object is provided it takes precedence over _.templateSettings
values.
Note: In the development build _.template
utilizes sourceURLs for easier debugging.
For more information on precompiling templates see lodash's custom builds documentation.
For more information on Chrome extension sandboxes see Chrome's extensions documentation.
[string='']
(string): The template string.[options]
(Object): The options object.[options.escape]
(RegExp): The HTML "escape" delimiter.[options.evaluate]
(RegExp): The "evaluate" delimiter.[options.imports]
(Object): An object to import into the template as free variables.[options.interpolate]
(RegExp): The "interpolate" delimiter.[options.sourceURL]
(string): The sourceURL of the template's compiled source.[options.variable]
(string): The data object variable name.(Function): Returns the compiled template function.
// using the "interpolate" delimiter to create a compiled templatevar compiled = _.template('hello <%= user %>!');compiled({ 'user': 'fred' });// => 'hello fred!' // using the HTML "escape" delimiter to escape data property valuesvar compiled = _.template('<b><%- value %></b>');compiled({ 'value': '<script>' });// => '<b>&lt;script&gt;</b>' // using the "evaluate" delimiter to execute JavaScript and generate HTMLvar compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');compiled({ 'users': ['fred', 'barney'] });// => '<li>fred</li><li>barney</li>' // using the internal `print` function in "evaluate" delimitersvar compiled = _.template('<% print("hello " + user); %>!');compiled({ 'user': 'barney' });// => 'hello barney!' // using the ES delimiter as an alternative to the default "interpolate" delimitervar compiled = _.template('hello ${ user }!');compiled({ 'user': 'pebbles' });// => 'hello pebbles!' // using custom template delimiters_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;var compiled = _.template('hello {{ user }}!');compiled({ 'user': 'mustache' });// => 'hello mustache!' // using backslashes to treat delimiters as plain textvar compiled = _.template('<%= "\\<%- value %\\>" %>');compiled({ 'value': 'ignored' });// => '<%- value %>' // using the `imports` option to import `jQuery` as `jq`var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';var compiled = _.template(text, { 'imports': { 'jq': jQuery } });compiled({ 'users': ['fred', 'barney'] });// => '<li>fred</li><li>barney</li>' // using the `sourceURL` option to specify a custom sourceURL for the templatevar compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });compiled(data);// => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector // using the `variable` option to ensure a with-statement isn't used in the compiled templatevar compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });compiled.source;// => function(data) {// var __t, __p = '';// __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';// return __p;// } // using the `source` property to inline compiled templates for meaningful// line numbers in error messages and a stack tracefs.writeFileSync(path.join(cwd, 'jst.js'), '\ var JST = {\ "main": ' + _.template(mainText).source + '\ };\');
_.trim([string=''], [chars=whitespace])
Removes leading and trailing whitespace or specified characters from string
.
[string='']
(string): The string to trim.[chars=whitespace]
(string): The characters to trim.(string): Returns the trimmed string.
_.trim(' abc ');// => 'abc' _.trim('-_-abc-_-', '_-');// => 'abc' _.map([' foo ', ' bar '], _.trim);// => ['foo', 'bar']
_.trimLeft([string=''], [chars=whitespace])
Removes leading whitespace or specified characters from string
.
[string='']
(string): The string to trim.[chars=whitespace]
(string): The characters to trim.(string): Returns the trimmed string.
_.trimLeft(' abc ');// => 'abc ' _.trimLeft('-_-abc-_-', '_-');// => 'abc-_-'
_.trimRight([string=''], [chars=whitespace])
Removes trailing whitespace or specified characters from string
.
[string='']
(string): The string to trim.[chars=whitespace]
(string): The characters to trim.(string): Returns the trimmed string.
_.trimRight(' abc ');// => ' abc' _.trimRight('-_-abc-_-', '_-');// => '-_-abc'
_.trunc([string=''], [options], [options.length=30], [options.omission='...'], [options.separator])
Truncates string
if it's longer than the given maximum string length. The last characters of the truncated string are replaced with the omission string which defaults to "...".
[string='']
(string): The string to truncate.[options]
(Object|number): The options object or maximum string length.[options.length=30]
(number): The maximum string length.[options.omission='...']
(string): The string to indicate text is omitted.[options.separator]
(RegExp|string): The separator pattern to truncate to.(string): Returns the truncated string.
_.trunc('hi-diddly-ho there, neighborino');// => 'hi-diddly-ho there, neighbo...' _.trunc('hi-diddly-ho there, neighborino', 24);// => 'hi-diddly-ho there, n...' _.trunc('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': ' '});// => 'hi-diddly-ho there,...' _.trunc('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': /,? +/});// => 'hi-diddly-ho there...' _.trunc('hi-diddly-ho there, neighborino', { 'omission': ' [...]'});// => 'hi-diddly-ho there, neig [...]'
_.unescape([string=''])
The inverse of _.escape
; this method converts the HTML entities &amp;
, &lt;
, &gt;
, &quot;
, &#39;
, and &#96;
in string
to their corresponding characters.
Note: No other HTML entities are unescaped. To unescape additional HTML entities use a third-party library like he.
[string='']
(string): The string to unescape.(string): Returns the unescaped string.
_.unescape('fred, barney, &amp; pebbles');// => 'fred, barney, & pebbles'
_.words([string=''], [pattern])
Splits string
into an array of its words.
[string='']
(string): The string to inspect.[pattern]
(RegExp|string): The pattern to match words.(Array): Returns the words of string
.
_.words('fred, barney, & pebbles');// => ['fred', 'barney', 'pebbles'] _.words('fred, barney, & pebbles', /[^, ]+/g);// => ['fred', 'barney', '&', 'pebbles']
“Utility” Methods
_.attempt(func)
Attempts to invoke func
, returning either the result or the caught error object. Any additional arguments are provided to func
when it's invoked.
func
(Function): The function to attempt.(*): Returns the func
result or error object.
// avoid throwing errors for invalid selectorsvar elements = _.attempt(function(selector) { return document.querySelectorAll(selector);}, '>_>'); if (_.isError(elements)) { elements = [];}
_.callback([func=_.identity], [thisArg])
Creates a function that invokes func
with the this
binding of thisArg
and arguments of the created function. If func
is a property name the created callback returns the property value for a given element. If func
is an object the created callback returns true
for elements that contain the equivalent object properties, otherwise it returns false
.
_.iteratee
[func=_.identity]
(*): The value to convert to a callback.[thisArg]
(*): The this
binding of func
.(Function): Returns the callback.
var users = [ { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }]; // wrap to create custom callback shorthands_.callback = _.wrap(_.callback, function(callback, func, thisArg) { var match = /^(.+?)__([gl]t)(.+)$/.exec(func); if (!match) { return callback(func, thisArg); } return function(object) { return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3]; };}); _.filter(users, 'age__gt36');// => [{ 'user': 'fred', 'age': 40 }]
_.constant(value)
Creates a function that returns value
.
value
(*): The value to return from the new function.(Function): Returns the new function.
var object = { 'user': 'fred' };var getter = _.constant(object); getter() === object;// => true
_.identity(value)
This method returns the first argument provided to it.
value
(*): Any value.(*): Returns value
.
var object = { 'user': 'fred' }; _.identity(object) === object;// => true
_.matches(source)
Creates a function that performs a deep comparison between a given object and source
, returning true
if the given object has equivalent property values, else false
.
Note: This method supports comparing arrays, booleans, Date
objects, numbers, Object
objects, regexes, and strings. Objects are compared by their own, not inherited, enumerable properties. For comparing a single own or inherited property value see _.matchesProperty
.
source
(Object): The object of property values to match.(Function): Returns the new function.
var users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false }]; _.filter(users, _.matches({ 'age': 40, 'active': false }));// => [{ 'user': 'fred', 'age': 40, 'active': false }]
_.matchesProperty(path, srcValue)
Creates a function that compares the property value of path
on a given object to value
.
Note: This method supports comparing arrays, booleans, Date
objects, numbers, Object
objects, regexes, and strings. Objects are compared by their own, not inherited, enumerable properties.
path
(Array|string): The path of the property to get.srcValue
(*): The value to match.(Function): Returns the new function.
var users = [ { 'user': 'barney' }, { 'user': 'fred' }]; _.find(users, _.matchesProperty('user', 'fred'));// => { 'user': 'fred' }
_.method(path, [args])
Creates a function that invokes the method at path
on a given object. Any additional arguments are provided to the invoked method.
path
(Array|string): The path of the method to invoke.[args]
(...*): The arguments to invoke the method with.(Function): Returns the new function.
var objects = [ { 'a': { 'b': { 'c': _.constant(2) } } }, { 'a': { 'b': { 'c': _.constant(1) } } }]; _.map(objects, _.method('a.b.c'));// => [2, 1] _.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c');// => [1, 2]
_.methodOf(object, [args])
The opposite of _.method
; this method creates a function that invokes the method at a given path on object
. Any additional arguments are provided to the invoked method.
object
(Object): The object to query.[args]
(...*): The arguments to invoke the method with.(Function): Returns the new function.
var array = _.times(3, _.constant), object = { 'a': array, 'b': array, 'c': array }; _.map(['a[2]', 'c[0]'], _.methodOf(object));// => [2, 0] _.map([['a', '2'], ['c', '0']], _.methodOf(object));// => [2, 0]
_.mixin([object=lodash], source, [options])
Adds all own enumerable function properties of a source object to the destination object. If object
is a function then methods are added to its prototype as well.
Note: Use _.runInContext
to create a pristine lodash
function to avoid conflicts caused by modifying the original.
[object=lodash]
(Function|Object): The destination object.source
(Object): The object of functions to add.[options]
(Object): The options object.[options.chain=true]
(boolean): Specify whether the functions added are chainable.(*): Returns object
.
function vowels(string) { return _.filter(string, function(v) { return /[aeiou]/i.test(v); });} _.mixin({ 'vowels': vowels });_.vowels('fred');// => ['e'] _('fred').vowels().value();// => ['e'] _.mixin({ 'vowels': vowels }, { 'chain': false });_('fred').vowels();// => ['e']
_.noConflict()
Reverts the _
variable to its previous value and returns a reference to the lodash
function.
(Function): Returns the lodash
function.
var lodash = _.noConflict();
_.noop()
A no-operation function that returns undefined
regardless of the arguments it receives.
var object = { 'user': 'fred' }; _.noop(object) === undefined;// => true
_.property(path)
Creates a function that returns the property value at path
on a given object.
path
(Array|string): The path of the property to get.(Function): Returns the new function.
var objects = [ { 'a': { 'b': { 'c': 2 } } }, { 'a': { 'b': { 'c': 1 } } }]; _.map(objects, _.property('a.b.c'));// => [2, 1] _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');// => [1, 2]
_.propertyOf(object)
The opposite of _.property
; this method creates a function that returns the property value at a given path on object
.
object
(Object): The object to query.(Function): Returns the new function.
var array = [0, 1, 2], object = { 'a': array, 'b': array, 'c': array }; _.map(['a[2]', 'c[0]'], _.propertyOf(object));// => [2, 0] _.map([['a', '2'], ['c', '0']], _.propertyOf(object));// => [2, 0]
_.range([start=0], end, [step=1])
Creates an array of numbers (positive and/or negative) progressing from start
up to, but not including, end
. If end
is not specified it's set to start
with start
then set to 0
. If end
is less than start
a zero-length range is created unless a negative step
is specified.
[start=0]
(number): The start of the range.end
(number): The end of the range.[step=1]
(number): The value to increment or decrement by.(Array): Returns the new array of numbers.
_.range(4);// => [0, 1, 2, 3] _.range(1, 5);// => [1, 2, 3, 4] _.range(0, 20, 5);// => [0, 5, 10, 15] _.range(0, -4, -1);// => [0, -1, -2, -3] _.range(1, 4, 0);// => [1, 1, 1] _.range(0);// => []
_.runInContext([context=root])
Create a new pristine lodash
function using the given context
object.
[context=root]
(Object): The context object.(Function): Returns a new lodash
function.
_.mixin({ 'foo': _.constant('foo') }); var lodash = _.runInContext();lodash.mixin({ 'bar': lodash.constant('bar') }); _.isFunction(_.foo);// => true_.isFunction(_.bar);// => false lodash.isFunction(lodash.foo);// => falselodash.isFunction(lodash.bar);// => true // using `context` to mock `Date#getTime` use in `_.now`var mock = _.runInContext({ 'Date': function() { return { 'getTime': getTimeMock }; }}); // or creating a suped-up `defer` in Node.jsvar defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
_.times(n, [iteratee=_.identity], [thisArg])
Invokes the iteratee function n
times, returning an array of the results of each invocation. The iteratee
is bound to thisArg
and invoked with one argument; (index).
n
(number): The number of times to invoke iteratee
.[iteratee=_.identity]
(Function): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(Array): Returns the array of results.
var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));// => [3, 6, 4] _.times(3, function(n) { mage.castSpell(n);});// => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2` _.times(3, function(n) { this.cast(n);}, mage);// => also invokes `mage.castSpell(n)` three times