convert uppercase and lowercase in javascript [duplicate]

别说谁变了你拦得住时间么 提交于 2021-01-27 06:34:19

问题


I want to make a code that converts uppercase and lowercase in Javascript.

For example, 'Hi, Stack Overflow.' ----> 'hI, sTACK oVERFLOW'

How can I do it?


回答1:


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;
  }
}



回答2:


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)



回答3:


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



回答4:


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'



回答5:


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());



回答6:


A function which will do this for you:

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


来源:https://stackoverflow.com/questions/40192262/convert-uppercase-and-lowercase-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!