-1

My program must change the case of my word on UpperCase or LowerCase.

Example:

word: "cAPS"

solution: "Caps"

All good, but.

My program works well with one word.

The program checks case of my word by two first symbols(Uppercase or Lower case) But when deal going to sentence I have a problem.

I do not understand, how method I must use. Maybe need to use an array or cycle to doing this?

My problem:

word: "wHY DO wE NEED cAPS lOCK?"

Code of my program:

let newWord = 'cAPS'
word = newWord

if (word.length > 1) {
  var lengthWord = word.length
  if (word.substring(1) == word.toUpperCase().substring(1)) {
    newWord = word.toUpperCase(0, 1).substring(0, 1) +
      word.toLowerCase().substring(1)
    console.log(newWord)
  } else if (word.substring(0) == word.toUpperCase().substring(0)) {
    newWord = word.toLowerCase().substring(0)
    console.log(newWord)
  } else if (word.substring(0, 1) == word.toUpperCase().substring(0, 1)) {
    newWord = word
    console.log(newWord)
  }

}
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
Dan
  • 1
  • 2

3 Answers3

0

Do you mean something like this?

let s = "wHY DO wE NEED cAPS lOCK?" ;

let finalS = s.split(' ').reduce((result,word)=>{
   let cleanWord = [...word].map((char,index)=>index===0 ? char.toUpperCase() : char.toLowerCase() ).join('');
   return `${result} ${cleanWord}`
},'');

console.log(finalS);
Vahid Alimohamadi
  • 4,900
  • 2
  • 22
  • 37
0

Solution 1: Capitalize first letter of every word

word = newWord.split(' ').map(innerWord => `${innerWord[0].toUpperCase()}${innerWord.split('').slice(1).join('')}`);

Solution 2: Capitalize only the first letter of a set of words

word = `${newWord[0].toUpperCase()}${newWord.split('').slice(1).join('')}`
0xLogN
  • 3,289
  • 1
  • 14
  • 35
0

Its Simple and easy way convert string UpperCase of each word .

var mystring = "wHY DO wE NEED cAPS lOCK"
var mystring_split = mystring.split(" ")
complete = []

mystring_split.forEach(myFunction);
 function myFunction(item, index) {
   word= item
  if (word.length > 1)
{
var lengthWord = word.length
if (word.substring(1) == word.toUpperCase().substring(1)) {
   newWord = word.toUpperCase(0, 1).substring(0, 1) + 
   word.toLowerCase().substring(1)
   complete.push(newWord)
}
return complete

}
}

console.log( complete.join(" "))
Sajid Ali
  • 21
  • 5