Line data Source code
1 1 : String getCamelCase(String text, {String separator = ''}) {
2 : List<String> words =
3 3 : _groupIntoWords(text).map(_upperCaseFirstLetter).toList();
4 3 : words[0] = words[0].toLowerCase();
5 :
6 1 : return words.join(separator);
7 : }
8 :
9 1 : String _upperCaseFirstLetter(String word) {
10 5 : return '${word.substring(0, 1).toUpperCase()}${word.substring(1).toLowerCase()}';
11 : }
12 :
13 3 : final RegExp _upperAlphaRegex = RegExp(r'[A-Z]');
14 3 : final RegExp _symbolRegex = RegExp(r'[ ./_\-]');
15 :
16 1 : List<String> _groupIntoWords(String text) {
17 1 : StringBuffer sb = StringBuffer();
18 1 : List<String> words = [];
19 2 : bool isAllCaps = !text.contains(RegExp('[a-z]'));
20 :
21 3 : for (int i = 0; i < text.length; i++) {
22 2 : String char = String.fromCharCode(text.codeUnitAt(i));
23 3 : String nextChar = (i + 1 == text.length
24 : ? null
25 3 : : String.fromCharCode(text.codeUnitAt(i + 1)));
26 :
27 2 : if (_symbolRegex.hasMatch(char)) {
28 : continue;
29 : }
30 :
31 1 : sb.write(char);
32 :
33 : bool isEndOfWord = nextChar == null ||
34 2 : (_upperAlphaRegex.hasMatch(nextChar) && !isAllCaps) ||
35 2 : _symbolRegex.hasMatch(nextChar);
36 :
37 : if (isEndOfWord) {
38 2 : words.add(sb.toString());
39 1 : sb.clear();
40 : }
41 : }
42 :
43 : return words;
44 : }
|