[Solved] Alternate casing for a string algorithm


You can create a regex to capture words and process using your function to parse individual words.

For demonstration purpose, I have used the regex: /[a-z0-9]/gi (assuming you will have only alphanumeric characters in a word. Please update the regex if you can have other characters as well.)

Following is a sample:

function toCapitalize(s) {
  var chars = s.toLowerCase().split("");
  for (var i = 0; i < chars.length; i += 2) {
    chars[i] = chars[i].toUpperCase();
  }
  return chars.join("");
}

function CaPiTaLiZe(s) {
  var parsedString = s.replace(/[a-z0-9]+/gi, toCapitalize)
  console.log(parsedString)
  return parsedString
}

// Giving expected o/p for the following i/p                      
CaPiTaLiZe('Hello') //         ==> 'HeLlo'
CaPiTaLiZe('hello world') //   ==>  'HeLlO WoRlD'

//But it does not give expected output for the following i/p.
CaPiTaLiZe('hello world testing 123') //  ==>   'HeLlO WoRlD TeStInG 123'
CaPiTaLiZe(' Hello World ') //            ==>      ' HeLlO WoRlD '
CaPiTaLiZe(' I will see you in 2wo years') // ==>  ' I WiLl SeE YoU In 2wO YeArS'

5

solved Alternate casing for a string algorithm