toCamelCase method

String toCamelCase({
  1. bool isLowerCamelCase = false,
})

Convert the given string to camelCase.

By default isLowerCamelCase is set as false and the given string is converted into UpperCamelCase. That means the first letter of String is converted into upperCase.

If the isLowerCamelCase is set to true then camelCase produces lowerCamelCase. That means the first letter of String is converted into lowerCase.

If the String is empty, this method returns this.

Example :

print('hello World'.toCamelCase()); // HelloWorld
print('hello_World'.toCamelCase()); // HelloWorld
print('hello World'.toCamelCase(isLowerCamelCase: true)); // helloWorld

Implementation

String toCamelCase({bool isLowerCamelCase = false}) {
  final Pattern pattern = RegExp(r'[ _]');

  Iterable<String> itrStr = split(pattern);
  final List<String> answer = [];

  final String first = itrStr.first;
  answer.add(isLowerCamelCase ? first.toLowerCase() : first.capitalize());

  itrStr = itrStr.skip(1);

  if (contains(pattern)) {
    for (var string in itrStr) {
      answer.add(string.capitalize());
    }
  } else {
    return isLowerCamelCase ? toLowerCase() : capitalize();
  }

  return answer.join();
}