超火js库: Lodash API例子 (持续更新~~~)

lodash.js是一款超火的js库,在npm上平均周下载量达到了惊人的12,374,096,github start36K!大量框架都用到了lodash,包括拥有123kstart的vue本文对比lodash英文文档,加上一些小栗子和个人的经验~~,希望能帮到你们

lodash采用了immutable的思想,永远不会改变原数据,而是会返回一个新的结果
String 字符串操作
camelCase 转换驼峰命名
_.camelCase([string=”])
console.log(_.camelCase(‘Foo Bar’))
// => ‘fooBar’

console.log(_.camelCase(‘–foo-bar–‘))
// => ‘fooBar’

console.log(_.camelCase(‘__FOO_BAR__’))
// => ‘fooBar’

console.log(_.camelCase(‘/\__FOO_BAR__*\9’))
// ‘fooBar9’

console.log(_.camelCase(‘fooBarbar_bar’))
// fooBarbarBar
字符串中非数字和字母都会被过滤掉,然后再转换为驼峰
capitalize 转换大写
_.capitalize([string=”])
console.log(_.capitalize(‘FRED’));
// => ‘Fred’
联想: 同string.prototype.toLocaleUpperCase();
deburr 清理符号
_.capitalize([string=”])
deburr转换 Latin-1 Supplement和Latin Extended-A 为普通拉丁字母并且移除变音符号
_.deburr(‘déjà vu’);
// => ‘deja vu’
一般用不到…
endsWith 判断是否是某个字符串结尾
_.endsWith([string=”], [target], [position=string.length])
console.log(_.endsWith(‘abcdef3’, ‘c’, 3))
// true
console.log(_.endsWith(‘abcdef3’, ‘c’, 2))
// false
主要是第三个参数,不填表示检查整个字符串,有值代表从左截取几个字符,从截取的字符中进行判断ECMAScript 6中已经加入string.prototype.endsWith()方法

escape 转义html实体字符
_.escape([string=”])
会将&装换成&amp, < -> &lt, > -> &gt ” -> &quot。其他转义字符,如:×(乘号),÷(除号)等不会转义,请用he这样的专业处理转义的库
console.log(_.escape(`a as <a> &’”” *`))
// a as &lt;a&gt; &amp;&#39;&quot;&quot; *
escapeRegExp 转义正则表达式特殊字符
_.escapeRegExp([string=”])
正则表达式中的特殊字符都会加”处理
console.log(_.escapeRegExp(‘[lodash](https://lodash.com…\\\\/)’))
// \[lodash\]\(https://lodash\.com\.\.\.\\\\/\)
kebabCase 转换成kebabCase格式
总结: 存在四种case格式

CamelCase: TheQuickBrownFoxJumpsOverTheLazyDog

SnakeCase: the_quick_brown_fox_jumps_over_the_lazy_dog

KebabCase: the-quick-brown-fox-jumps-over-the-lazy-dog

Studlycaps: tHeqUicKBrOWnFoXJUmpsoVeRThElAzydOG

查看case的具体文档
其他转换case语法通camelCase

lowerCase 转换小写
_.lowerCase([string=”])
_.lowerCase(‘–Foo-Bar–‘);
// => ‘foo bar’

_.lowerCase(‘fooBar’);
// => ‘foo bar’

_.lowerCase(‘__FOO_BAR__’);
// => ‘foo bar’
通capitalize
联想: string.prototype.toLocaleLowerCase
lowerFirst 转换第一个字符为小写
console.log(_.lowerFirst(‘DS’))
// dS
console.log(_.lowerFirst(‘__DS’))
// __DS
无法过滤非字母字符
pad 填充字符
_.pad([string=”], [length=0], [chars=’ ‘])有三个参数: 原字符串,长度,填充字符
如果原字符串长度短于给定的长度,则原字符串左右两边会填充指定字符(默认为空格),如果不能平均分配则会被截断。
_.pad(‘abc’, 8);
// => ‘ abc ‘

_.pad(‘abc’, 8, ‘_-‘);
// => ‘_-abc_-_’

_.pad(‘abc’, 3);
// => ‘abc’

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理