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.
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.
Share Improve this question edited Nov 21, 2020 at 13:08 Dave Newton 160k27 gold badges260 silver badges308 bronze badges asked Jan 27, 2016 at 3:05 ssssss 7171 gold badge8 silver badges20 bronze badges 1-
1
'lower UPPER'.replace(/./g, c => c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase())
– zerkms Commented Jan 27, 2016 at 4:07
2 Answers
Reset to default 6You 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 mands in your console:
console.log("".toUpperCase);
console.log("".toUpperCase.toString());
The results of both are function toUpperCase() { [native code] }
.
Happy coding!
Use ES6 Syntax:
You could use ES6 features JavaScript has to offer which would reduce the source code:
const convertString = str => [...str].map(char => char === char.toUpperCase() ? char.toLowerCase() : char.toUpperCase()).join('');
console.log(convertString("lower UPPER"));