Mohamed Hegazy
Mohamed Hegazy

Reputation: 273

how to convert Uppercase to lower case and vice versa without using regexp in JavaScript?

I am a complete beginner and I was trying to do this using loops and if conditionals, however it never worked, I am suspecting the problem is with my if conditional.

here is my code and thanks in advance.

function alter(a){






        for (var i = 0; i<a.length; i++){



            if (a[i] === a[i].toUpperCase()){ a[i] = a[i].toLowerCase(); }

            else if (a[i] === a[i].toLowerCase()){ a[i] = a[i].toUpperCase(); }

        }


        console.log(a);



}

Upvotes: 0

Views: 3734

Answers (4)

menomanabdulla
menomanabdulla

Reputation: 175

Convert uppercase to lower case and vice versa simply with ES6 feature

const caseToggler = (str) => str.split('').map(item => item === item.toUpperCase() ? item.toLowerCase() : item.toUpperCase()).join('')

console.log(caseToggler('ab1By'))

Upvotes: 0

akhtarvahid
akhtarvahid

Reputation: 9769

let str = 'HelloWorld';

let UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    LOWER='abcdefghijklmnopqrstuvwxyz',
    res1=[],len=str.length;

for(let i=0;i<len;i++){
  if(UPPER.indexOf(str[i])!==-1)
    res1.push(str[i].toLowerCase())
  else if(LOWER.indexOf(str[i]!==-1))
    res1.push(str[i].toUpperCase())
}
console.log('solution-1: '+res1.join(''))
 

let res2=[];
for(let i=0;i<len;i++){
    if(UPPER.includes(str[i]))
  res2.push(str[i].toLowerCase())
  else if(LOWER.includes(str[i]))
   res2.push(str[i].toUpperCase())
}

console.log('solution 2: '+res2.join(''))

Upvotes: 0

JoeL
JoeL

Reputation: 710

var hello = "hElLO";
var newWord = [];

for (i=0; i<hello.length; i++) {
  if (hello[i] == hello[i].toLowerCase()) {
      newWord[i] = hello[i].toUpperCase();
  }
  else {
    newWord[i] = hello[i].toLowerCase();
  }
}

alert(newWord.join(""));

Upvotes: 2

bapibopi
bapibopi

Reputation: 62

As @SLaks mentioned, strings in javascript are immutable, meaning that you can't actually change the contents of one. Instead you could create a new empty string and add to that

function alter(string) {
  var newString = ''
  for (var i = 0; i < string.length; i++) {
    newString += string[i] === string[i].toUpperCase() ? string[i].toLowerCase() : string[i].toUpperCase()
  }
  return newString
}

Upvotes: 3

Related Questions