I want to make code that converts uppercase and lowercase in JavaScript.
For example, 'Hi, Stack Overflow.' → 'hI, sTACK oVERFLOW'
How can I do it?
You could run over each character, and then covert it to lowercase if it's in uppercase, to uppercase if it's in lowercase or take it as is if it's neither (if it's a comma, colon, etc):
str = 'Hi, Stack Overflow.';
res = '';
for (var i = 0; i < str.length; ++i) {
c = str[i];
if (c == c.toUpperCase()) {
res += c.toLowerCase();
} else if (c == c.toLowerCase()) {
res += c.toUpperCase();
} else {
res += c;
}
}
You can try this simple solution using map()
var a = 'Hi, Stack Overflow!'
var ans = a.split('').map(function(c){
return c === c.toUpperCase()
? c.toLowerCase()
: c.toUpperCase()
}).join('')
console.log(ans)
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