awesome-string
Version:
The ultimate JavaScript string library
32 lines (31 loc) • 1.06 kB
JavaScript
import coerceToBoolean from 'helper/boolean/coerce_to_boolean';
import coerceToString from 'helper/string/coerce_to_string';
/**
* Converts the first character of `subject` to upper case. If `restToLower` is `true`, convert the rest of
* `subject` to lower case.
*
* @function capitalize
* @static
* @since 1.0.0
* @memberOf Case
* @param {string} [subject=''] The string to capitalize.
* @param {boolean} [restToLower=false] Convert the rest of `subject` to lower case.
* @return {string} Returns the capitalized string.
* @example
* as.capitalize('apple');
* // => 'Apple'
*
* as.capitalize('aPPle', true);
* // => 'Apple'
*/
export default function capitalize(subject, restToLower) {
let subjectString = coerceToString(subject);
const restToLowerCaseBoolean = coerceToBoolean(restToLower);
if (subjectString === '') {
return '';
}
if (restToLowerCaseBoolean) {
subjectString = subjectString.toLowerCase();
}
return subjectString.substr(0, 1).toUpperCase() + subjectString.substr(1);
}