frontEnd_book icon indicating copy to clipboard operation
frontEnd_book copied to clipboard

如何把一个字符串的大小写取反(大写变小写小写变大写),例如 ’AbC' 变成 'aBc'

Open hanyueqiang opened this issue 4 years ago • 0 comments

实现思路: 1.把字符串用split分割为数组,遍历数组 2.对遍历的每个值进行toUpperCase()全等对比,如果相等证明这个字母原就是大写,进行小写转换,如果不相等说明取反成功,进行大写转换

代码实现

function changeStr(str) {
      const arr = str.split('');
      const changeArr = arr.map(val => val = (val === val.toUpperCase()) ? val.toLowerCase() : val.toUpperCase());
      return changeArr.join('');
    }
    console.log(changeStr('abC123&ddD'))

注意:遇到特殊字符或者数字字符串,会返回原字符,不做处理

hanyueqiang avatar Dec 03 '20 09:12 hanyueqiang