我们需要编写一个JavaScript函数,该函数接受一个字符串并构造一个新字符串,其中所有大写字符都转换为小写,所有小写字符都转换为大写。
让我们为该函数编写代码-
以下是代码-
const str = 'The Case OF tHis StrinG Will Be FLiPped';
const isUpperCase = char => char.charCodeAt(0) >= 65 && char.charCodeAt(0)
<= 90;
const isLowerCase = char => char.charCodeAt(0) >= 97 &&
char.charCodeAt(0) <= 122;
const flipCase = str => {
let newStr = '';
const margin = 32;
for(let i = 0; i < str.length; i++){
const curr = str[i];
if(isLowerCase(curr)){
newStr += String.fromCharCode(curr.charCodeAt(0) - margin);
}else if(isUpperCase(curr)){
newStr += String.fromCharCode(curr.charCodeAt(0) + margin);
}else{
newStr += curr;
};
};
return newStr;
};
console.log(flipCase(str));输出结果
控制台中的输出:-
tHE cASE of ThIS sTRINg wILL bE flIpPED