尽管编写一个将单词首字母大写的函数是很容易的,例如:
"hello" => "Hello" "hi there" => "Hi there"
但如何使用Ramda JS以点无式样式编写它呢?
尽管编写一个将单词首字母大写的函数是很容易的,例如:
"hello" => "Hello" "hi there" => "Hi there"
但如何使用Ramda JS以点无式样式编写它呢?
您可以部分应用 replace
函数,并使用运行于第一个字符上的 toUpper
正则表达式:
const capitalize = R.replace(/^./, R.toUpper);
它会是这样的:
const capitalize = R.compose(
R.join(''),
R.juxt([R.compose(R.toUpper, R.head), R.tail])
);
演示(在 ramdajs.com REPL 中)。
并进行小修改以处理 null
值。
const capitalize = R.compose(
R.join(''),
R.juxt([R.compose(R.toUpper, R.head), R.tail])
);
const capitalizeOrNull = R.ifElse(R.equals(null), R.identity, capitalize);
ifElse(equals(null), identity,
,否则我认为这就是使用 Maybe
monad 的地方。 - zerkmsisNil
代替equals(null)
了! - tmikeschuunless
函数可以取代ifElse
和identity
的组合,这样可能更易于阅读。具体做法是:const capitalizeIfNotNil = R.unless(R.isNil, capitalize);
- Nicolás Fantone我建议使用R.lens
:
const char0 = R.lens(R.head, R.useWith(R.concat, [R.identity, R.tail]));
R.over(char0, R.toUpper, 'ramda');
// => 'Ramda'
str[0].toUpperCase() + str.slice(1)
更快[但这也不是OP所要求的,所以无关紧要])。
https://jsfiddle.net/960q1e31/ (您需要打开控制台并运行该Fiddle才能查看结果)如果有人正在寻找一个将第一个字母大写并且同时将其他字母小写的解决方案,那么这里就是:
const capitalize = R.compose(R.toUpper, R.head);
const lowercaseTail = R.compose(R.toLower, R.tail);
const toTitle = R.converge(R.concat, [capitalize, lowercaseTail]);
toTitle('rAmdA');
// -> 'Ramda'
replace
的第二个参数是一个字符串而不是一个函数。对我来说没有用。 - Damian GreenR.replace
。第二个参数也可以是一个函数,请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Syntax。 - lax4mike