Convert a camelized string into a lowercased one with a custom separator.
看简介咱们知道 decamelize 这个包主要是用来分隔字符串。git
官方例子:github
const decamelize = require('decamelize'); decamelize('unicornRainbow'); //=> 'unicorn_rainbow' decamelize('unicornRainbow', '-'); //=> 'unicorn-rainbow'
略。框架
'use strict'; const xRegExp = require('xregexp'); /** * @param {string} text 文本 * @param {string} separator 分隔符 */ module.exports = (text, separator) => { if (typeof text !== 'string') { throw new TypeError('Expected a string'); } separator = typeof separator === 'undefined' ? '_' : separator; const regex1 = xRegExp('([\\p{Ll}\\d])(\\p{Lu})', 'g'); const regex2 = xRegExp('(\\p{Lu}+)(\\p{Lu}[\\p{Ll}\\d]+)', 'g'); return text .replace(regex1, `$1${separator}$2`) .replace(regex2, `$1${separator}$2`) .toLowerCase(); };
其实比较复杂的字符串处理都要用到正则,这里也不例外,做者用了一个 xregexp 的第三方正则拓展库,而核心代码主要是([\p{Ll}\d])(\p{Lu})
和 (\p{Lu}+)(\p{Lu}[\p{Ll}\d]+)
这两句正则,单元测试
这两句正则讲人话就是:(组1:匹配小写字母)(组2:匹配大写字母)
and (组1:匹配连续的大写字母)(组2:匹配小写字母)
这样咱们就能看懂了,把匹配的的内容替换成 组1 + 分隔符 + 组2
,这样就起到了对原字符串分隔的做用。测试
测试框架用的 ava,脚本略。ui
做者很聪明的利用正则组的用法,把一个简单的分隔功能作到了简单化,让我再次体会到正则的牛掰。spa