Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert uppercase and lowercase in javascript [duplicate]

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?

like image 272
kk2 Avatar asked Dec 19 '22 12:12

kk2


2 Answers

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;
  }
}
like image 177
Mureinik Avatar answered Feb 13 '23 22:02

Mureinik


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)
like image 21
Pranesh Ravi Avatar answered Feb 13 '23 23:02

Pranesh Ravi