I am attempting to take a string of numbers and iterate through that number. When there are two odd numbers adjacent to one another, I want to separate them with '-'.
For example, 999463 would become 9-9-9463.
const str = "999463"
const numberWithDash = []
for (let i = 0; i < str.length; i++) {
if (str[i] % 2 !== 0 && str[i + 1] % 2 !== 0) {
numberWithDash.push(str[i] + '-')
} else {
numberWithDash.push(str[i])
}
};
console.log(numberWithDash.join(''))
This returns "9-9-9463-". Why is this adding an additional dash on the end of my code? I think this is because the final number in the string is odd, thereby it is being passed through the if statement, instead of the else stament.
If I amend 'i < str.length -1' then I just cut off the last number entirely, so that isn't right either. I think I need to make my if statement stricter by adding another condition to check if str[i] is a number, but not sure where to start.