用JavaScript替换字符串
我们需要编写一个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