Goal: Write a method that turns a string into camel case.
My code:
String.prototype.camelCase=function(){ if (this === "") { return ""; } else { var arr = this.trim().split(' '); for (var i = 0; i < arr.length; i++) { arr[i] = arr[i][0].toUpperCase() + arr[i].slice(1); } return arr.join(''); } }
The code works fine except for when the input is an empty string, ""
. like "".camelCase();
.
The console gives me this error
TypeError: Cannot read property 'toUpperCase' of undefined at String.camelCase at Test.describe._ at /runner/frameworks/javascript/cw-2.js:179:21 at Promise._execute at Promise._resolveFromExecutor at new Promise at Object.describe at Object.handleError at ContextifyScript.Script.runInThisContext at Object.exports.runInThisContext
This is from codewars.
It seems that the empty string is bypassing the if
statement and the code stops when .toUpperCase()
is called on ""
.
Not sure why this is happening, thanks for any help!
edit: Solved thanks to @kevcomedia! Switched this === ''
to this.length === 0