Catalog
  1. 1. Ada
  2. 2. Beck
  3. 3. Helen
  4. 4. Irene
  5. 5. Mia
  6. 6. Jack
反转一个字符串里面的大小写,其它字符不变

如:输入字符串aBcD,返回字符串AbCd

Ada

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//A-Z 65-90
// a-z 97-122
//A - a = 32
function parseStr (str){
var result = '';
for(var i= 0;i<str.length;i++){
var temp = str.charAt(i);
var code = temp.charCodeAt();
if('a' <= temp && temp <= 'z'){
temp= String.fromCharCode(code-32);
} else if('A' <= temp && temp <= 'Z'){
temp= String.fromCharCode(code+32);
}

result += temp;
}
return result;
}

console.log(parseStr('aBcD'))

Beck

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function reverseCase(str) {
let charCodeStr = '';
const lowerStart = 'a';
const upperStart = 'A'
const diff = Math.abs(lowerStart.charCodeAt(0) - upperStart.charCodeAt(0));
for (let index = 0; index < str.length; index++) {
let currentChartCode = str.charCodeAt(index);
if (currentChartCode >= 65 && currentChartCode < 91) {
currentChartCode = currentChartCode + diff;
} else if (currentChartCode >= 97 && currentChartCode < 123) {
currentChartCode = currentChartCode - diff;
}
charCodeStr += String.fromCharCode(currentChartCode);
}
return charCodeStr;
}

// console.log(reverseCase('abcIasd'))

Helen

1
2
3
4
5
6
7
8
9
10
11
12
// a.先判断是大写还是小写,再做相应改变
function reverseCase(str) {
let outStr = '';
for (const key in str) {
let item = str[key];
/[a-z]/.test(item) && (outStr += item.toUpperCase());
/[A-Z]/.test(item) && (outStr += item.toLowerCase());
/[^a-zA-Z]/.test(item) && (outStr += item);
}
return outStr;
}
console.log(reverseCase('aBcDeeeeeeeEDS'));

Irene

1
2
3
4
5
6
function test(item) {
return item
.split('')
.map((item, index) => item.charCodeAt(0) < 90 ? item.toLowerCase() : item.toUpperCase())
.join('')
}

Mia

1
2
3
4
5
6
7
8
9
10
11
12
13
function f3(str){
return str.split("")
.map(function(item,i){
var charCode = item.charCodeAt();
console.log(i);
if(charCode<91){
return item.toLowerCase();
}else{
return item.toUpperCase();
}
}).join("");
}
f3("aBcD");

Jack

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function changeStr(str){
return(str.split("")
.map(
function (index){
let outStr = index.charCodeAt();
if(outStr < 91){
return index.toLowerCase()
}else{
return index.toUpperCase()
}
}
).join("")
)
}
Author: Erealm
Link: http://erealmsoft.github.io/2019/09/28/purefunc/purefunc-reverse-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.

Comment