I'm looking through the code for kibo.js and found this function:
开发者_开发百科Kibo.capitalize = function(string) {
return string.toLowerCase().replace(/^./, function(match) { return match.toUpperCase(); });
};
Anyone have any ideas why they might use this instead of just .toUpperCase?
PS - Kibo is found at https://github.com/marquete/kibo/blob/master/kibo.js
It basically converts the entire string to lower case first, and then capitalizes just the first letter.
capitalize:
TEST => Test
test => Test
teST => Test
...as opposed to toUpperCase:
test => TEST
teST => TEST
Test => TEST
toLowerCase:
TeST => test
TEST => test
tesT => test
Some languages also have a titleize
method which capitalizes the first letter of each word, as in a title/proper name:
mary poppins => Mary Poppins
a lovely and talented => A Lovely and Talented Title
what a title! => What a Title!
the meaning of life => The Meaning of Life
hello, world! => Hello, World!
Notice that it doesn't capitalize "and", "of", "the", etc. unless they are the first word in the string.
toUpperCase
converts all letters to upper case letters. This function, Kibo.capitalize
, first converts all letters to lower case and then converts only the first letter (/^./
) of the string to an upper case letter.
Kibo.capitalize('hello') // returns 'Hello'
'hello'.toUpperCase() // returns 'HELLO'
The function, well, capitalizes the string, i.e. turning the first letter to upper case and the following letters — to lowercase.
console.log(Kibo.capitalize('alEx'));
/*
* Outputs:
* 'Alex'
*/
>>> capitalize("hi mom")
"Hi mom"
>>> capitalize("HI MOM")
"Hi mom"
>>> capitalize("Hi Mom")
"Hi mom"
精彩评论