Home > Software design >  javascript / for-loop even and odd letters from text
javascript / for-loop even and odd letters from text

Time:07-15

I want to select even letters and odd letters from text, console.log show mi (199) [' ', ' ', ' ', ' ', ' '.... How can I fix it ?


btn.addEventListener('click', function() {
  //console.log(newText)  ok

  let evenletters = []

  for (let i = 0; i < newText.length; i  ) {
    if(newText[i] % 2 === 0) {
      evenletters.push(newText[i])
    }
  }
  console.log(evenletters)
})


CodePudding user response:

I'm guessing you are coming from C or another language that can treat a char as an int. What you want to do in JS is use .charCodeAt

let evenletters = []
let newText = 'Hello there how are you?'
  for (let i = 0; i < newText.length; i  ) {
    if(newText.charCodeAt(i) % 2 === 0) {
      evenletters.push(newText[i])
    }
  }
  console.log(evenletters)

  • Related