The loop repeats adding characters “!?.,” even though it shouldn’t

I wanted to create a simple function that turns a sentence into NATO phonetic alphabet. The loop works fine for the alphabet but creates a strange character problem. My code:

const alphabet = ["Alfa", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", 
"Juliett", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec", "Romeo", "Sierra", "Tango", 
"Uniform", "Victor", "Whiskey", "Xray", "Yankee", "Zulu"];

function phoneticAlph(words) {
let translatedTxt = "";
for (let i = 0; i < words.length; i++) {
    for (let x = 0; x < alphabet.length; x++) {
        if (words[i].toUpperCase() === alphabet[x][0]) {
            translatedTxt += `${alphabet[x]} `;
        } else if (words[i] === "!" || words[i] === "?" || words[i] === "," || words[i] === ".") {
            translatedTxt += words[i];
        }
     }
 }
 console.log(translatedTxt)
}

phoneticAlph("!I.a,m!Robot")

This appears in the console:

!!!!!!!!!!!!!!!!!!!!!!!!!!India ..........................Alfa ,,,,,,,,,,,,,,,,,,,,,,,,,,Mike 
!!!!!!!!!!!!!!!!!!!!!!!!!!Romeo Oscar Bravo Oscar Tango

I completely don’t understand what happened or how to fix it to display the characters correctly. I will be very grateful for your help and for explaining what actually happened.

Answer

The problem is the else if inside the second for cycle. For each special characters the first if is always skipped ,instead the else if is always hitted. Move the else if part outside of the second cycle for.

const alphabet = ["Alfa", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", 
"Juliett", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec", "Romeo", "Sierra", "Tango", 
"Uniform", "Victor", "Whiskey", "Xray", "Yankee", "Zulu"];

function phoneticAlph(words) {
let translatedTxt = "";
for (let i = 0; i < words.length; i++) {
    for (let x = 0; x < alphabet.length; x++) {
        if (words[i].toUpperCase() === alphabet[x][0]) {
            translatedTxt += `${alphabet[x]} `;
        }
     }
     if (words[i] === "!" || words[i] === "?" || words[i] === "," || words[i] === ".") {
        translatedTxt += `${words[i]} ` ;
    }
 }
 console.log(translatedTxt)
}

phoneticAlph("!I.a,m!Robot")

Leave a Reply

Your email address will not be published. Required fields are marked *