5

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?

1
  • did you try something ? Commented Oct 22, 2016 at 12:43

6 Answers 6

6

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; } } 
Sign up to request clarification or add additional context in comments.

2 Comments

See also this answer for a little more advanced solution: stackoverflow.com/a/38703925/1743938
It's generally not considered mutating a string directly (by accessing it's index). It's usually preferred to convert it to an array (using .split() without any parameter), then iterate over the array and reassemble the string with .join(). Just as an idea.
3

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)

Comments

0
<!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> 

Comments

0

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('') } 

1 Comment

The CodePen link is broken (404).
-1
var input = 'Hi, Stack Overflow.' var arr = input.split(' '); alert(arr); var output = arr.map(function(elem){ return (elem[0].toLowerCase() + elem.substring(1,elem.length).toUpperCase()); }); alert(output.join()); 

Comments

-1

var hi = 'Hi, Stack Overflow.'; var hI = hi.split(""); for(var i=0; i<hI.length; i++) { if(hI[i] == hI[i].toLowerCase()) hI[i] = hI[i].toUpperCase(); else if(hI[i] == hI[i].toUpperCase()) hI[i] = hI[i].toLowerCase(); } hI = hI.join(""); alert(hI); //'hI, sTACK oVERFLOW'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.