# Spinal Tap - For Loop Execution Question for Non Regex Solution

Hi there, I’m trying to solve this algorithm without using any regex. What I would like to do is something like this:

``````function spinalCase(str) {
var arr = str.split('');

for (var i = 0;  i < arr.length - 1; i++){
//if the char is a " " or "_" replace with "-"
if (arr[i] === " " || arr[i] === "_"){
arr[i] = "-";
} else {
//otherwise, check if the next char is upper and the current char is lower,
//if true splice appropriately
if (isUpper(arr[i+1]) && isLower(arr[i])){
arr.splice(i+1, 0, "-");
}
}
}

return arr.join('').toLowerCase();
}

function isUpper(x){
return x === x.toUpperCase();
}

function isLower(x){
return x === x.toLowerCase();
}

spinalCase('AllThe-small Things');
``````

When I try to run this code I actually get an infinite loop warning and the program will not run. I’m not sure why this is so if someone could explain that would be gret. Is this because I am changing the length of the array during the loop? When the loop is first executed and arr.length - 1 is calculated is it a fixed value for the duration of the entire loop? Or is it recalculated with every iteration?

Thank you everyone

@Swoodend, since you’re splicing with a delete count of 0, it’s constantly increasing the length of arr.
So your i variable will never reach the end of your array.

is there a reason you’re not using RegEx?
The code is very short and simple with it…

Hm. Could you explain why it will not reach the end of the loop. I understand that I am increasing the length off arr, but isn’t the stop condition (arr.length -1) in the for loop tested every iteration?

For instance, if I increase the length of arr by 3, wont (arr.length - 1) also increase by 3, and, instead of being an infinite loop it will just iterate 3 more times? I dont understand why this isn’t the case.

Thanks!

let say the string is “HelloWorld”.

at the iteration where i = 4, your if condition will evaluate to true for upper and lower, so it will insert “-”.
“Hello-World”

at the next iteration (i = 5)…
isUpper(arr[6]) = true (W)
isLower(arr[5]) = true (-)

resulting in “Hello–World”

next iteration would result in "Hello—World"
Then “Hello----World”…

wash, rinse, repeat…

Thanks 8-up!

That makes sense I didn’t know and did not test that isLower("-") returns TRUE! I thought that punctuation would return undefined or something falsey.

Really appreciate the help. I’m not sure why I chose to not use regex, I think this is just what I started writing and I wanted to stick with it.

Thanks again.