Skip to content Skip to sidebar Skip to footer

Inverse String Case

I'm trying to write a function that takes the string and changes all the lowercase letters to uppercase and vice versa. 'lower UPPER' would translate to 'LOWER upper' Heres what I

Solution 1:

You have just about everything correct, except for inside of your if statement. You're setting n equal to its toLowerCase or toUpperCasemethod, not its return value. You need to call those methods and set n equal to their return values:

var convertString = function (str) {
    var s = '';
    var i = 0;
    while (i < str.length) {
        var n = str.charAt(i);
        if (n == n.toUpperCase()) {
            // *Call* toLowerCase
            n = n.toLowerCase();
        } else {
            // *Call* toUpperCase
            n = n.toUpperCase();
        }

        i += 1;
        s += n; 
    }
    return s;
};

convertString("lower UPPER");

The output that you're getting ('function toUpperCase() { [native code] }...) is the result of each method being converted to a string, then concatenated to your result string. You can achieve the same result by running either of these commands in your console:

  • console.log("".toUpperCase);
  • console.log("".toUpperCase.toString());

The results of both are function toUpperCase() { [native code] }.

Happy coding!

Solution 2:

Use ES6 Syntax:

You could use ES6 features JavaScript has to offer which would reduce the source code:

constconvertString = str => [...str].map(char => char === char.toUpperCase() ? char.toLowerCase() : char.toUpperCase()).join('');

console.log(convertString("lower UPPER"));

Post a Comment for "Inverse String Case"