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 have:
var convertString = function (str){
var s = '';
var i = 0;
while (i < str.length) {
var n = str.charAt(i);
if (n == n.toUpperCase()) {
n = n.toLowerCase;
}
else {
n = n.toUpperCase;
}
i +=1;
s += n;
}
return s;
};
convertString("lower UPPER");
I'm using this website to work and am getting a pretty weird message outputted.
Here is a pic of what happens after I run it.
You have just about everything correct, except for inside of your if statement. You're setting n equal to its toLowerCase or toUpperCase method, 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With