Tell us what’s happening:
This is not clean code - I saw other solutions with /\W, split, match, etc) but it passes all tests in codepen && it’s my first attempt at this problem. Why it does not pass in the FCC editor?
Your code so far
const regEx = /[A-Z]+/g;
const reg2 = /\,+/g;
const reg3 = /\s+/g;
const reg4 = /\_+/g;
let newAr = []
let newSt = ''
function spinalCase(str) {
for(let i = 0; i < str.length; i++){
if(str[i].match(regEx) && i !=0){
newAr.push("-"+str[i])
}
else{
newAr.push(str[i])
//console.log("newStr: "+newAr)
}
newSt = newAr.toString().toLowerCase().replace(reg2, "").replace(reg3, "").replace(reg4, "")
}
console.log("typeof newSt : "+ typeof newSt)
console.log("newSt : "+newSt)
return newSt
}
spinalCase('This Is Spinal Tap');
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36.
Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.
Example:
var myGlobal = [1];
function returnGlobal(arg) {
myGlobal.push(arg);
return myGlobal;
} // unreliable - array gets longer each time the function is run
function returnLocal(arg) {
var myLocal = [1];
myLocal.push(arg);
return myLocal;
} // reliable - always returns an array of length 2
And once you’ve dealt with the globals issue (@ArielLeslie is exactly right – the variables being defined outside your function means the values are persisting, and the string just gets longer and longer each time), there is one more test that will fail:
spinalCase("Teletubbies say Eh-oh");
will fail, because you’re putting a hyphen before a capital letter. In this case, however, the word say is lower-case, and still needs to be spinal-cased.