toCamelCase function
Converts a string input
to camel case format.
If the input
is null or empty, an empty string is returned.
The function trims leading and trailing whitespace from the input
and splits it into an array of words using underscores, spaces, and hyphens
as delimiters. It then converts the first word to lowercase and appends
the capitalized version of each subsequent word (except the first word)
to the result. The remaining characters in each word are converted to
lowercase.
Example: toCamelCase('hello_world') => 'helloWorld' toCamelCase('hello-world') => 'helloWorld' toCamelCase('hello world') => 'helloWorld' toCamelCase('HelloWorld') => 'helloWorld'
Returns the converted string in camel case format.
Implementation
String toCamelCase(String? input) {
if (input == null || input.isEmpty) return '';
final words = input.trim().split(RegExp(r'[_\s-]+|(?<=[a-z])(?=[A-Z])'));
final buffer = StringBuffer()..write(words[0].toLowerCase());
for (var i = 1; i < words.length; i++) {
if (words[i].length > 1) {
buffer
..write(words[i][0].toUpperCase())
..write(words[i].substring(1).toLowerCase());
} else {
buffer.write(words[i].toUpperCase());
}
}
return buffer.toString();
}