超火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 SupplementLatin 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'
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章