在 JavaScript 中对字符串进行大小写替换

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/26 9:48:17

我们需要编写一个 JavaScript 函数,该函数接受一个字符串并构造一个新字符串,其中原始字符串中的所有大写字符都转换为小写,原始字符串中的所有小写字符都转换为大写。

例如:如果字符串是 −

const str = 'The Case OF tHis StrinG Will Be FLiPped';

输出

那么输出应该是 −

const output = 'tHE cASE of ThIS sTRINg wILL bE flIpPED';

示例

其代码为 −

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

相关文章


有用资源