当前位置: > > > JS - Lodash工具库的使用详解3(String字符串操作函数)

JS - Lodash工具库的使用详解3(String字符串操作函数)

三、String 字符串操作函数

1,将字符串转换成驼峰命名

camelCase 函数可以将字符串中非数字和字母的字符都过滤掉,然后再转换为驼峰。
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

2,首字母大写

capitalize 函数可以转换字符串 string 首字母为大写,剩下为小写。
console.log(_.capitalize('FRED'));  // => 'Fred'

3,判断是否以某个字符串开头

startsWith 函数可以检查一个字符串是否以指定字符串开头。
_.startsWith('abc', 'a');  // => true
_.startsWith('abc', 'b');  // => false

4,判断是否以某个字符串结尾

endsWith 函数可以检查一个字符串是否以指定字符串结尾。
_.endsWith('abc', 'c');  // => true
_.endsWith('abc', 'b');  // => false

5,转译 HTML 特殊字符

(1)escape 函数可以转义 string 中的 &<>"和 字符为 HTML 实体字符。
console.log(_.escape(`a  as <a> &'"" *`));

(2)unescape 函数的作用和 escape 正好相反,它可以转换 string 字符串中的 HTML 实体 &amp;&lt;&gt;&quot;&#39; &#96; 为对应的字符。
console.log(_.unescape(`a  as &lt;a&gt; &amp;&#39;&quot;&quot; *`));

6,填充字符

Lodash 提供了 padpadStartpadEnd 这三个函数来填充字符。
  • pad(左右填充):如果原字符串长度短于给定的长度,则原字符串左右两边会填充指定字符(默认为空格),如果不能平均分配则会被截断。
  • padStart(在开始处填充字符):如果原字符串长度短于给定的长度,则原字符串左边会填充指定字符(默认为空格),如果填充字符超出长度则会被截断。
  • padEnd(在结尾处填充字符):如果原字符串长度短于给定的长度,则原字符串右边会填充指定字符(默认为空格),如果填充字符超出长度则会被截断。
/** pad(左右填充) **/
_.pad('abc', 8);   // => '  abc   '
_.pad('abc', 8, '_-');   // => '_-abc_-_'
_.pad('abc', 3);   // => 'abc'

/** padStart(在开始处填充字符) **/
_.padStart('abc', 6);   // => '   abc'
_.padStart('abc', 6, '_-');   // => '_-_abc'
_.padStart('abc', 3);   // => 'abc'

/** padEnd(在结尾处填充字符) **/
_.padEnd('abc', 6);   // => 'abc   '
_.padEnd('abc', 6, '_-');   // => 'abc_-_'
_.padEnd('abc', 3);   // => 'abc'

7,重复指定字符串

repeat 函数可以重复 string 字符串 n 次, 默认 1 次。
_.repeat('*', 3);   // => '***'
_.repeat('abc', 2);   // => 'abcabc'
_.repeat('abc', 0);   // => ''

8,字符串截断

    truncate 函数可以截断 string 字符串,如果字符串超出了限定的最大值。 被截断的字符串后面会以 omission 代替,omission 默认是 "..."。
函数第1个参数是要截断的字符串,第2个参数是选项对象,选项对象有如下可选值:
  • length:允许的最大长度。
  • omission:超出后的代替字符。
  • separator:截断点。
_.truncate('hi-diddly-ho there, neighborino');   // => 'hi-diddly-ho there, neighbo...'
 
_.truncate('hi-diddly-ho there, neighborino', {
  'length': 24,
  'separator': ' '
});   // => 'hi-diddly-ho there,...'
 
_.truncate('hi-diddly-ho there, neighborino', {
  'length': 24,
  'separator': /,? +/
});   // => 'hi-diddly-ho there...'
 
_.truncate('hi-diddly-ho there, neighborino', {
  'omission': ' [...]'
});   // => 'hi-diddly-ho there, neig [...]'
评论0