ez-string-toolkit
Version:
A simple and easy-to-use string utility library with essential string manipulation functions
80 lines (74 loc) • 1.92 kB
JavaScript
/**
* Simple String Utilities Library
* A collection of useful string manipulation functions
*/
/**
* Capitalizes the first letter of a string
* @param {string} str - The input string
* @returns {string} The string with first letter capitalized
*/
function capitalize(str) {
if (typeof str !== 'string' || str.length === 0) {
return str;
}
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
/**
* Converts a string to camelCase
* @param {string} str - The input string
* @returns {string} The camelCase string
*/
function toCamelCase(str) {
if (typeof str !== 'string') {
return str;
}
return str
.toLowerCase()
.replace(/[^a-zA-Z0-9]+(.)/g, (match, chr) => chr.toUpperCase());
}
/**
* Reverses a string
* @param {string} str - The input string
* @returns {string} The reversed string
*/
function reverse(str) {
if (typeof str !== 'string') {
return str;
}
return str.split('').reverse().join('');
}
/**
* Counts the number of words in a string
* @param {string} str - The input string
* @returns {number} The number of words
*/
function wordCount(str) {
if (typeof str !== 'string') {
return 0;
}
return str.trim().split(/\s+/).filter(word => word.length > 0).length;
}
/**
* Truncates a string to a specified length
* @param {string} str - The input string
* @param {number} maxLength - The maximum length
* @param {string} suffix - The suffix to add (default: '...')
* @returns {string} The truncated string
*/
function truncate(str, maxLength, suffix = '...') {
if (typeof str !== 'string') {
return str;
}
if (str.length <= maxLength) {
return str;
}
return str.substring(0, maxLength - suffix.length) + suffix;
}
// Export all functions
module.exports = {
capitalize,
toCamelCase,
reverse,
wordCount,
truncate
};