Loops and if statements

Hello! Can you help me with this? I need to get from a tale of glass to a Tale of Glass I don’t know why this doesn’t work, can you explain me why? I thought that with for each I can modify the original arr but here I feel like the array is the same as at the beginning.
the code:

class Formatter {
  //add static methods here
  
  static capitalize(str){
    let cap = str.charAt(0).toUpperCase();
    str = str.slice(1);
    return cap+str;
  }

  static sanitize(str){
    return str.replace(/[^\w'\-\s]/g, '')
  }
  //'the', 'a', 'an', 'but', 'of', 'and', 'for', 'at', 'by', and 'from'
  static titleize(str){
    let arr= str.split(" ")
     arr.forEach( word=> { console.log(word)

      if(word!=='the'||word!=="a"||word!=='but'||word!=="of"||word!=='and'||word!=="for"||word!=='at'||word!=="by"||word!=="from"){
        console.log("if")
        console.log(Formatter.capitalize(word))
        word = Formatter.capitalize(word)
      }
    })

  

    console.log("arr", arr)
    let newStr= arr.join(" ")
    // console.log(newStr)
    return newStr
  }
}

Formatter.titleize("a tale of two cities")

@fadime try http://pythontutor.com/visualize.html#mode=display
I had the same problem and FCC community suggested this.

1 Like

thank you ! That resource it is cool! But it didin’t help me to understand :frowning:

Hello there,

I would think about this if statement:

if(word!=='the'||word!=="a"||word!=='but'||word!=="of"||word!=='and'||word!=="for"||word!=='at'||word!=="by"||word!=="from"){

It is not doing what you want.

Hope this helps

1 Like

Thanks! I solved it :smiley:

class Formatter {
  //add static methods here
  
  static capitalize(str){
    let cap = str.charAt(0).toUpperCase();
    str = str.slice(1);
    return cap+str;
  }

  static sanitize(str){
    return str.replace(/[^\w'\-\s]/g, '')
  }
  //'the', 'a', 'an', 'but', 'of', 'and', 'for', 'at', 'by', and 'from'
  static titleize(str){
    let arr= str.split(" ")
    let newArr= [];
     arr.forEach( word=> { 
      //  console.log(word)

      if(word === 'the'|| word === "a"|| word === 'but'||word ==="of"||word ==='and'||word ==="for"||word==='at'||word==="by"||word ==="from"){
        // console.log("if")
        // console.log(Formatter.capitalize(word))
       newArr.push(word)
      }else{
         word = Formatter.capitalize(word)
         newArr.push(word)
      }
      
    })

  

    // console.log("arr", newArr)
    let newStr= newArr.join(" ")
    // console.log(newStr)
    return newStr
  }
}

let newTitle = Formatter.titleize("a tale of two cities")