Skip to content

Commit

Permalink
improve camelcase behavior for all caps words and acronyms. see mout#201
Browse files Browse the repository at this point in the history
  • Loading branch information
millermedeiros committed Nov 17, 2014
1 parent b584edb commit d464bc8
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
24 changes: 19 additions & 5 deletions src/string/camelCase.js
Expand Up @@ -6,11 +6,25 @@ define(['../lang/toString', './replaceAccents', './removeNonWord', './upperCase'
str = toString(str);
str = replaceAccents(str);
str = removeNonWord(str)
.replace(/[\-_]/g, ' ') //convert all hyphens and underscores to spaces
.replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE
.replace(/\s+/g, '') //remove spaces
.replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase
return str;
.replace(/[\-_]/g, ' '); // convert all hyphens and underscores to spaces

// handle acronyms
// matches lowercase chars && uppercase words
if (/[a-z]/.test(str) && /^|\s[A-Z]+\s|$/.test(str)) {
// we convert any word that isn't all caps into lowercase
str = str.replace(/\s(\w+)/g, function(word, m) {
return /^[A-Z]+$/.test(m) ? word : lowerCase(word);
});
} else if (/\s/.test(str)) {
// if it doesn't contain an acronym and it has spaces we should
// convert every word to lowercase
str = lowerCase(str);
}

return str
.replace(/\s[a-z]/g, upperCase) // convert first char of each word to UPPERCASE
.replace(/^\s*[A-Z]+/g, lowerCase) // convert first word to lowercase
.replace(/\s+/g, ''); // remove spaces
}
return camelCase;
});
22 changes: 22 additions & 0 deletions tests/spec/string/spec-camelCase.js
Expand Up @@ -40,5 +40,27 @@ define(['mout/string/camelCase'], function (camelCase) {
expect( camelCase(void 0) ).toBe('');
});

it('should work with UPPER_CASE input', function() {
expect( camelCase('SOME_TEXT') ).toBe('someText');
});

it('should preserve camelCase input', function() {
expect( camelCase('loremIpsum') ).toBe('loremIpsum');
});

it('should preserve acronyms if string contains lowercase', function() {
expect( camelCase('XML HTTP request') ).toBe('xmlHTTPRequest');
expect( camelCase('XML HTTP Request') ).toBe('xmlHTTPRequest');
expect( camelCase('XML_HTTP_request') ).toBe('xmlHTTPRequest');
expect( camelCase('XML_HTTP_Request') ).toBe('xmlHTTPRequest');
expect( camelCase('XML-HTTP-request') ).toBe('xmlHTTPRequest');
});

it('should ignore acronyms if input is all uppercase', function() {
expect( camelCase('XML HTTP REQUEST') ).toBe('xmlHttpRequest');
expect( camelCase('XML_HTTP_REQUEST') ).toBe('xmlHttpRequest');
expect( camelCase('XML-HTTP-REQUEST') ).toBe('xmlHttpRequest');
});

});
});

0 comments on commit d464bc8

Please sign in to comment.