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; } } <!DOCTYPE html> <html> <head> <title>hello</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> </head> <body> <script> $(document).ready(function(){ var x = 'Hi, Stack Overflow.'; alert(caseAlter(x)); function caseAlter(txt){ var output = ""; for(var i = 0; i < txt.length; i++){ if(txt[i] == txt[i].toUpperCase()){ output += txt[i].toLowerCase(); }else{ output += txt[i].toUpperCase(); } } return output; } }); </script> </body> </html> A function which will do this for you (also at CodePen):
function reverseCase(input) { var output = [] for(var char in input) { var character = input[char] if(character == character.toUpperCase()) output.push(character.toLowerCase()) else output.push(character.toUpperCase()) } return output.join('') }