Search code examples
javascriptuppercaselowercase

Turn lowercase letters of a string to uppercase and the inverse


let message = "heY, WHAt are you dOING?";
let count_changes = 0;
let isLetter = (letter) => {
    if (('a'<=letter && letter >='z') || ('A'<=letter && letter >='Z')) {
        return letter;
    } else {
        return -1;
    }
}

for(let i = 0; i <= message.length; i++) {
    if (isLetter(i) && message[i].toLowerCase()) {
        message[i].toUpperCase();
        count_changes++;
        console.log(message[i].toLowerCase());
    }
    else if (isLetter(i) && message[i].toUpperCase()) {
        message[i].toLowerCase();
        count_changes++;
    }
    else {
        console.error('Bad stirng');
    }
}

Hello, I want to use the function isLetter to check the string message every character and when i use isLetter in the for loop to check in the if statement whether i is a Letter or not and also if its Lowercase letter later to when there is a change to Uppercase i increment count_changes++. Again with the second if statement if also i is Letter and in this case Uppercase letter then if change to lowercase letter to increment the count_changes++ so the count_changes to be my final result thank you


Solution

  • From what I understand, you want to count the number of characters in the string and return a string where all uppercase characters are replaced with lowercase characters and all lowercase characters are replaced with uppercase characters. Additionally, you want to increment countChanges once for every character changed.

    This code should do what you want:

    let message = "heY, WHAt are you dOING?";
    let countChanges = 0;
    let isLetter = c => c.toLowerCase() !== c.toUpperCase();
    let isLowerCase = c => c.toLowerCase() === c;
    
    let flippedMessage = Array.from(message).map((c)=>{
        if(!isLetter(c)){
            return c;
        }
        countChanges++;
        // return uppercase character if c is a lowercase char
        if(isLowerCase(c)){
            return c.toUpperCase();
        }
        // Here, we know c is an uppercase character, so return the lowercase
        return c.toLowerCase();
    }).join('');
    
    // flippedMessage is "HEy, whaT ARE YOU Doing?"
    // countChanges is 18