@simongrasinovski/str-utils
Version:
A lightweight utility library for effortless string manipulation. Simplify common tasks like case validation, conversion and formatting with easy-to-use functions that enhance your JavaScript applications
36 lines (34 loc) • 1.34 kB
JavaScript
;
var removeConsecutiveSpaces = require('./removeConsecutiveSpaces');
var _require = require('./utils'),
ensureString = _require.ensureString;
/**
* Converts a string to Title Case.
*
* @function
* @param {string} input - The string to convert.
* @param {object} [options={}] - An optional configuration object.
* @param {boolean} [options.trimConsecutiveSpaces=true] - If true, consecutive spaces are trimmed.
* @returns {string} String in Title Case.
*
* @throws {TypeError} Throws an error if the input is not a string.
*
* @example
* const result = titleCase('helLo world fRom strIng utils');
* console.log(result); // 'Hello World From String Utils'
*/
module.exports = ensureString(function (input) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _options$trimConsecut = options.trimConsecutiveSpaces,
trimConsecutiveSpaces = _options$trimConsecut === void 0 ? true : _options$trimConsecut;
if (trimConsecutiveSpaces) {
input = removeConsecutiveSpaces(input);
}
var words = input.toLowerCase().split(' ');
var result = words.map(function (word) {
var firstLetter = word.charAt(0).toUpperCase();
var remainder = word.slice(1);
return "".concat(firstLetter).concat(remainder);
});
return result.join(' ');
});