Created
October 14, 2015 00:15
-
-
Save kirklewis/af3eac6756fb94b19ba3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function toCamelCase(str) { | |
//get the words from the string, would use \w but it includes underscores. | |
var words = str.match(/([a-zA-Z0-9]+)/g); | |
words = words.map(function(word, i){ | |
//ignore the first word otherwise its first letter will be capitalised. | |
if(i == 0) return word; | |
//capitalise first letter in each word and concatenate it onto the rest of itself. E.g. C + ode | |
return word.charAt(0).toUpperCase() + word.substr(1); | |
}); | |
//join the words back together, the end. | |
return words.join(''); | |
} | |
//Tests: camel_case_spec.js | |
var expect = chai.expect; | |
describe('toCamelCase', function() { | |
it('Should convert first letter of each word except the first, to upper case', function() { | |
expect(toCamelCase('do something')).to.equal('doSomething'); | |
expect(toCamelCase('do something else')).to.equal('doSomethingElse'); | |
expect(toCamelCase('underscore_me')).to.equal('underscoreMe'); | |
expect(toCamelCase('cat-jumps-up')).to.equal('catJumpsUp'); | |
expect(toCamelCase('1 ones and zeros 0')).to.equal('1OnesAndZeros0'); | |
expect(toCamelCase('one+two=three')).toEqual('oneTwoThree'); | |
expect(toCamelCase('non alpha nums?/!')).to.equal('nonAlphaNums'); | |
expect(toCamelCase('Caps-Lock')).to.equal('CapsLock'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment