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

发布于 2022-06-25 19:26:30 字数 274 浏览 945 评论 57

function processString (s) {
    var arr = s.split('');
    var new_arr = arr.map((item) => {
        return item === item.toUpperCase() ? item.toLowerCase() : item.toUpperCase();
    });
    return new_arr.join('');
}
console.log(processString('AbC'));

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(57

空城仅有旧梦在 2022-05-04 13:56:24

str = 'abcDEFg'
strRes = str.replace(/[a-zA-Z]/g,(item)=>{
if(item===item.toUpperCase()){
return item.toLowerCase();
}
return item.toUpperCase()
})

若沐 2022-05-04 13:56:24
function transString (str){
    return Array.prototype.reduce.call(str, (acc, cur) => acc + (cur === cur.toUpperCase() ? cur.toLowerCase() : cur.toUpperCase()), '');
}
妄想挽回 2022-05-04 13:56:24
function test(str) {
  str = str.split('').map(item => {
    if (item === item.toUpperCase()) {
      return item.toLowerCase();
    } else {
      return item.toUpperCase();
    }
  }).join('');
  console.log(str);
}
思念满溢 2022-05-04 13:56:24
function transString(str){
     return str.split('').map((item) =>{
          return item == item.toLowerCase() ? item.toUpperCase() : item.toLowerCase();
     }).join('');
}
夏九 2022-05-04 13:56:24
    /**
    @param: {str} 
    */
    function reversal(str) {
        let newstr = '';
        for(let i = 0 ; i < str.length; i++) {
            console.log(str[i].toUpperCase())
            newstr += (str[i] === str[i].toUpperCase() ? str[i].toLowerCase() : str[i].toUpperCase())
        }
        return newstr;
    }
    console.log(reversal('AbC'))
你在我安 2022-05-04 13:56:24
function tranStr(str) {
  if (typeof str !== 'string') return ''
  const splitStr = str.split('')
  return splitStr.reduce((res, s) => {
    if (/[a-z]/g.test(s)) {
      res += s.toLocaleUpperCase()
    } else if (/[A-Z]/g.test(s)) {
      res += s.toLocaleLowerCase()
    } else {
      res += s
    }
    return res
  }, '')
}
思念绕指尖 2022-05-04 13:56:24
/**
 * 把一个字符串的大小写取反(大写变小写小写变大写),例如 ’AbC' 变成 'aBc'
 * @param {*} str 
 */
function tranStr2(str) {
  if (typeof str !== 'string') return str
  return str.replace(/[a-zA-Z]/g, function(s) {
    return /[a-z]/g.test(s) ? s.toLocaleUpperCase() : /[A-Z]/g.test(s) ? s.toLocaleLowerCase() : s
  })
}
后eg是否自 2022-05-04 13:56:24
function transString(str) {
  if(typeof str !== 'string') return
  let strArr = str.split('')
  return strArr.reduce((acc, cur) => acc += (cur === cur.toUpperCase() ? cur.toLowerCase() : cur.toUpperCase()))
}

第一个字母没有转换吧==

冰雪梦之恋 2022-05-04 13:56:24
  reverseCase = function (s) {
    const isLowerCase = char => {
      const range = ['a'.charCodeAt(), 'z'.charCodeAt()];
      const charCode = char.charCodeAt();
      return charCode >= range[0] && charCode <= range[1];
    }
    const isUpperCase = char => {
      const range = ['A'.charCodeAt(), 'Z'.charCodeAt()];
      const charCode = char.charCodeAt();
      return charCode >= range[0] && charCode <= range[1];
    }
    return s.split('').map(char => {
      if (isLowerCase(char)) return char.toUpperCase();
      if (isUpperCase(char)) return char.toLowerCase();
    }).join('');
  }
空名 2022-05-04 13:56:24

用了3种实现方法处理千万级别长度字符,对比了下时间,分享给大家,for循环+unicode转行相对较快
function getRandomStr() {
let str = ''
let arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z"
]
for (let i = 0; i < 10000000; i++) {
let num = parseInt(Math.random() * 53)
str += arr[num]
}
return str
}

    function transformStr1() {
        console.time('生成1千万长度字符串用时')
        let str = getRandomStr()
        console.timeEnd('生成1千万长度字符串用时')
        // console.log(str)
        console.time('使用正则替换用时')
        let str1 = str.replace(/./g, (input) => {
            let num = input.charCodeAt(0)
            if (num >= 65 && num <= 90) {
                return String.fromCharCode(num + 32)
            } else {
                return String.fromCharCode(num - 32)
            }
        })
        console.timeEnd('使用正则替换用时')
        // console.log(str)
        console.time('使用for循环耗时')
        let str2 = ''
        for (let i = 0, len = str.length; i < len; i++) {
            let s = str[i]
            let num = s.charCodeAt(0)
            if (num >= 65 && num <= 90) {
                str2 += String.fromCharCode(num + 32)
            } else {
                str2 += String.fromCharCode(num - 32)
            }
        }
        console.timeEnd('使用for循环耗时')
        console.log(str1 === str2)
        console.time('使用toUppercase逐个转换耗时')
        let str3 = ''
        for (let i = 0, len = str.length; i < len; i++) {
            let s = str[i]
            let sUp = s.toUpperCase()
            if (sUp === s) {
                str3 += s.toLocaleLowerCase()
            } else {
                str3 += sUp
            }
        }
        console.timeEnd('使用toUppercase逐个转换耗时')
        console.log(str2 === str3)
        console.time('使用toUppercase转换字符')
    }

为啥不顺手把输出结果也贴出来 =。 =

森林迷了鹿 2022-05-04 13:56:24

用了3种实现方法处理千万级别长度字符,对比了下时间,分享给大家,for循环+unicode转行相对较快
function getRandomStr() {
let str = ''
let arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z"
]
for (let i = 0; i < 10000000; i++) {
let num = parseInt(Math.random() * 53)
str += arr[num]
}
return str
}

    function transformStr1() {
        console.time('生成1千万长度字符串用时')
        let str = getRandomStr()
        console.timeEnd('生成1千万长度字符串用时')
        // console.log(str)
        console.time('使用正则替换用时')
        let str1 = str.replace(/./g, (input) => {
            let num = input.charCodeAt(0)
            if (num >= 65 && num <= 90) {
                return String.fromCharCode(num + 32)
            } else {
                return String.fromCharCode(num - 32)
            }
        })
        console.timeEnd('使用正则替换用时')
        // console.log(str)
        console.time('使用for循环耗时')
        let str2 = ''
        for (let i = 0, len = str.length; i < len; i++) {
            let s = str[i]
            let num = s.charCodeAt(0)
            if (num >= 65 && num <= 90) {
                str2 += String.fromCharCode(num + 32)
            } else {
                str2 += String.fromCharCode(num - 32)
            }
        }
        console.timeEnd('使用for循环耗时')
        console.log(str1 === str2)
        console.time('使用toUppercase逐个转换耗时')
        let str3 = ''
        for (let i = 0, len = str.length; i < len; i++) {
            let s = str[i]
            let sUp = s.toUpperCase()
            if (sUp === s) {
                str3 += s.toLocaleLowerCase()
            } else {
                str3 += sUp
            }
        }
        console.timeEnd('使用toUppercase逐个转换耗时')
        console.log(str2 === str3)
        console.time('使用toUppercase转换字符')
    }

为啥不顺手把输出结果也贴出来 =。 =

用了3种实现方法处理千万级别长度字符,对比了下时间,分享给大家,for循环+unicode转行相对较快
function getRandomStr() {
let str = ''
let arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z"
]
for (let i = 0; i < 10000000; i++) {
let num = parseInt(Math.random() * 53)
str += arr[num]
}
return str
}

    function transformStr1() {
        console.time('生成1千万长度字符串用时')
        let str = getRandomStr()
        console.timeEnd('生成1千万长度字符串用时')
        // console.log(str)
        console.time('使用正则替换用时')
        let str1 = str.replace(/./g, (input) => {
            let num = input.charCodeAt(0)
            if (num >= 65 && num <= 90) {
                return String.fromCharCode(num + 32)
            } else {
                return String.fromCharCode(num - 32)
            }
        })
        console.timeEnd('使用正则替换用时')
        // console.log(str)
        console.time('使用for循环耗时')
        let str2 = ''
        for (let i = 0, len = str.length; i < len; i++) {
            let s = str[i]
            let num = s.charCodeAt(0)
            if (num >= 65 && num <= 90) {
                str2 += String.fromCharCode(num + 32)
            } else {
                str2 += String.fromCharCode(num - 32)
            }
        }
        console.timeEnd('使用for循环耗时')
        console.log(str1 === str2)
        console.time('使用toUppercase逐个转换耗时')
        let str3 = ''
        for (let i = 0, len = str.length; i < len; i++) {
            let s = str[i]
            let sUp = s.toUpperCase()
            if (sUp === s) {
                str3 += s.toLocaleLowerCase()
            } else {
                str3 += sUp
            }
        }
        console.timeEnd('使用toUppercase逐个转换耗时')
        console.log(str2 === str3)
        console.time('使用toUppercase转换字符')
    }

So要识趣 2022-05-04 13:56:24

用了3种实现方法处理千万级别长度字符,对比了下时间,分享给大家,for循环+unicode转行相对较快
function getRandomStr() {
let str = ''
let arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z"
]
for (let i = 0; i < 10000000; i++) {
let num = parseInt(Math.random() * 53)
str += arr[num]
}
return str
}

    function transformStr1() {
        console.time('生成1千万长度字符串用时')
        let str = getRandomStr()
        console.timeEnd('生成1千万长度字符串用时')
        // console.log(str)
        console.time('使用正则替换用时')
        let str1 = str.replace(/./g, (input) => {
            let num = input.charCodeAt(0)
            if (num >= 65 && num <= 90) {
                return String.fromCharCode(num + 32)
            } else {
                return String.fromCharCode(num - 32)
            }
        })
        console.timeEnd('使用正则替换用时')
        // console.log(str)
        console.time('使用for循环耗时')
        let str2 = ''
        for (let i = 0, len = str.length; i < len; i++) {
            let s = str[i]
            let num = s.charCodeAt(0)
            if (num >= 65 && num <= 90) {
                str2 += String.fromCharCode(num + 32)
            } else {
                str2 += String.fromCharCode(num - 32)
            }
        }
        console.timeEnd('使用for循环耗时')
        console.log(str1 === str2)
        console.time('使用toUppercase逐个转换耗时')
        let str3 = ''
        for (let i = 0, len = str.length; i < len; i++) {
            let s = str[i]
            let sUp = s.toUpperCase()
            if (sUp === s) {
                str3 += s.toLocaleLowerCase()
            } else {
                str3 += sUp
            }
        }
        console.timeEnd('使用toUppercase逐个转换耗时')
        console.log(str2 === str3)
        console.time('使用toUppercase转换字符')
    }

为啥不顺手把输出结果也贴出来 =。 =

贴上去了

放赐﹉ 2022-05-04 13:56:24

@wangminglmm 感谢,很直观

烏雲後面有陽光 2022-05-04 13:56:24

好像没看到用spread的,我写一下,用regex判断是否是字母, 以及用String.fromCharCode和String.prototype.charCodeAt()来切换大小写。

const flipByCharCode = (str) => [...str].map((char) => {
    let isAlphabet = /[a-z]/i.test(char);
    let isLowercase = /[a-z]/.test(char);

    return !isAlphabet ? char : String.fromCharCode(char.charCodeAt(0) + 32 * (isLowercase ? -1 : 1));
}).join('');

# 代码写成同行,对手机阅读不友好
const flipByCharCode = (str) => [...str].map((s) => !/[a-z]/i.test(s) ? s : String.fromCharCode(s.charCodeAt(0) + 32 * (/[a-z]/.test(s) ? -1 : 1))).join('');
眉目亦如画i 2022-05-04 13:56:24
const reverseCase = str => {
    let s = '';
    for(let i of str){
        if(i === i.toUpperCase()){
            s += i.toLowerCase();
        }else {
           s += i.toUpperCase();
        }
    }
    return s;
};
reverseCase('abCDeFgHe'); // "ABcdEfGhE"
挥剑断情 2022-05-04 13:56:24
var str = "AbC==-3.$%^&*……"


str.replace(/([a-zA-Z])/g, (match) => /[a-z]/.test(match) ? match.toUpperCase() : match.toLowerCase())
月亮坠入山谷 2022-05-04 13:56:24
function reverseCase(str){
    return str.split('').map(item => {
        return item === item.toUpperCase()? item.toLowerCase(): item.toUpperCase()}).join('');
};
reverseCase('abCDeFgHe'); // "ABcdEfGhE"
埋情葬爱 2022-05-04 13:56:24
str
.split('')
.map((char) => {
	const code = char.charCodeAt()
	if (code >= 97) {
		return String.fromCharCode(code - 32)
	} else {
		return String.fromCharCode(code + 32)
	}
})
.join('')
最冷一天 2022-05-04 13:56:24
let invertCase = (str)=>{
    let [uA,uZ,ua,uz] = ['A'.charCodeAt(), 'Z'.charCodeAt(), 'a'.charCodeAt(), 'z'.charCodeAt()]

    return Array.prototype.map.call(str, (item,index)=>{
        if (item.charCodeAt() >= uA && item.charCodeAt() <= uZ)
            return item.toLowerCase()
        else if (item.charCodeAt() >= ua && item.charCodeAt() <= uz)
            return item.toUpperCase()
        else
            return item
    }
    ).join('')
}
夏见 2022-05-04 13:56:24
const reverseChar= (c) => {
  const lc = c.toLowerCase()
  return c == lc ? c.toUpperCase() : lc
}
const reverseCase = (str) => {
  let len = str.length
  let res = ''
  for(let i=0; i<len; i++) {
    res += reverseChar(str[i])
  }
  return res
}
console.log(reverseCase('AbC'))
没︽人懂的悲伤 2022-05-04 13:56:24

@iotale
你这个只考虑了字母,如果有其他字符就行不通了

transStr('adASjOdapASJO!@#4123123.l124')
// "ADasJoDAPasjoA`CTQRSQRSNLQRT"

题目不是只包含字母嘛

栩栩如生 2022-05-04 13:56:24

const reverseCase = s=>s.split('').reduce((t,c)=>${t}${c.toUpperCase() === c?c.toLowerCase():c.toUpperCase()},'')

走野 2022-05-04 13:56:24
const toLowerUpperCase = (str = '') => {
    return str.split('').map(val => val === val.toUpperCase() ? val.toLowerCase() : val.toUpperCase()).join('')
}

console.log(toLowerUpperCase('AbC'));
临走之时 2022-05-04 13:56:24
'AbC'.split('').map(char => {
    let asciiNo = char.codePointAt(0)
    if (asciiNo >= 65 && asciiNo < 97) {
        return String.fromCodePoint(asciiNo + 32)
    } else {
        return String.fromCodePoint(asciiNo - 32)
    }
}).join('')
她比我温柔 2022-05-04 13:56:24

const change = str => {
let arr = str.split('').map(item => {
return item = item === item.toUpperCase() ? item.toLowerCase() : item.toUpperCase()
})
return arr.join('')
}
change('aBc') // AbC

折戟 2022-05-04 13:56:24
function transStr(str){
  console.log(str)
  return [...str].map((s) => {
    console.log(s)
    return s.toUpperCase() === s ? s.toLowerCase() : s.toUpperCase()
  }).join('')
}
const strTest = 'AbC'
console.log(transStr(strTest))
凉城凉梦凉人心 2022-05-04 13:56:24

function transStr(str) {
return str.split('').map(it => String.fromCharCode(it.charCodeAt()<91?it.charCodeAt()+32:it.charCodeAt()-32)).join('')
}

与风相奔跑 2022-05-04 13:56:24
function tranformText(text) {
  var text2 = text.toLowerCase();
  var result = "";
  for(let i = 0; i < text.length; i++) {
    if (text[i] === text2[i]) result+=text[i].toUpperCase();
    else result+=text2[i]
  }
  return result;
}

千と千尋 2022-05-04 13:56:24

function foo(s) {
return s.replace(/([a-zA-Z])/g, function (match, b, offset, string) {
return match < 'a' ? match.toLowerCase() : match.toUpperCase()
})
}

凉世弥音 2022-05-04 13:56:24

1、使用 toLowerCasetoUpperCase

function reverse(str) {
  var origin = str.split('')
  return origin.map(char => {
    if(char.toLowerCase() === char) {
      return char.toUpperCase()
    } else {
      return char.toLowerCase()
    }
  }).join('')
}

2、使用 fromCharCode

这种方法只适用于只存在英文字母的情况

function reverse(str) {
  var origin = str.split('')
  return origin.map(char => {
    let code = char.charCodeAt()
    if(code >= 97) {
      return String.fromCharCode(code - 32)
    } else {
      return String.fromCharCode(code + 32)
    }
  }).join('')
}
愿与i 2022-05-04 13:56:24
// 大写的A-Z 转码比较结果比  小写a 要小
function turn(str){
        const strArr = str.split('')
        return strArr.map(key=> key < 'a' ? key.toLowerCase() : key.toUpperCase()).join('')
    }
梅窗月明清似水 2022-05-04 13:56:24
let str = 'GuanWeiChang', result = '';
let UpperCaseIdx = [];
str.replace(/[A-Z]/g, function (match, idx) {
  UpperCaseIdx.push(idx);
});
for (let i = 0; i < str.length; i++) {
  const char = str[i];
  result += UpperCaseIdx.includes(i) ? char.toLowerCase() : char.toUpperCase();
}
console.log(result);
天荒地未老 2022-05-04 13:56:24
        var str = 'AbC'
        var reg = /([A-Z])|([a-z])/g
        var result = str.replace(reg, function (match, p1, p2) {
            if (p1) {
                return p1.toLowerCase()
            }
            if (p2) {
                return p2.toUpperCase()
            }
        })
        console.log(result)//aBc
终难愈 2022-05-04 13:56:24
const changeCase = (string) => {
	return [...string].reduce((total, item) => {
		total += (item.toLowerCase() == item ? item.toUpperCase() : item.toLowerCase())
		return total
	},'')
}
console.log(changeCase('AFDdhfaADvD'))
や莫失莫忘 2022-05-04 13:56:24
"AabBcZz123,./".replace(/[a-zA-Z]/g, c=>c.charCodeAt(0)<91?c.toLowerCase(): c.toUpperCase());
// 得到 'aABbCzZ123,./'
没有心的人〃 2022-05-04 13:56:24

function letterUpperCaseReserve(string){
let result = [...string].map(item =>{
if(/^[a-z]+$/.test(item)) return item.toUpperCase();
return item.toLowerCase();
})
return result.join('');
}

我只土不豪 2022-05-04 13:56:24

function reverse(str) { const list = str.split('').map(item => { return item.toLowerCase() === item ? item.toUpperCase() : item.toLowerCase() }) return list.join(''); }

   ` console.log(reverse('aBCd'), 'reverse(str)');`
旧伤慢歌 2022-05-04 13:56:24
//我也写了用ascall码的,只适用于英文字母字符串
function reverseNum(str) {
    let res = [];
    let arr = str.split('');
    let len = 'a'.charCodeAt();
    for(let i=0;i<arr.length;i++){
        let item = arr[i].charCodeAt();
        res.push(String.fromCharCode(item>=len?item-32:item+32));
    }
    return res.join('');
}
没有你我更好 2022-05-04 13:56:24
// Ascii码
 let res = []
    let str = 'Abc'
    for (let val of str) {
        // console.log(val);
        if (val.codePointAt(0) >= 65 && val.codePointAt(0) <= 90) {
            res.push(val.toLowerCase())
        }
        if (val.codePointAt(0) >= 97 && val.codePointAt(0) <= 122) {
            res.push(val.toUpperCase())
        }
    }
    console.log(res.join(''));
妖妓 2022-05-04 13:56:24
let isUpperCase = (s = String) => s.charCodeAt() > 64 && s.charCodeAt() < 91;
let isLowerCase = (s = String) => s.charCodeAt() > 96 && s.charCodeAt() < 123;
let reverseCharCase = (str = String) =>
  str
    .split("")
    .map((v, i) => (isLowerCase(v) ? v.toUpperCase() : v.toLowerCase()))
    .join("");
A君。 2022-05-04 13:56:24

function isLowerByAsciiCode(code){
    return code > 64 && code <91;
}

function isUpperByAsciiCode(code){
    return code > 96 && code <122;
}

function isLetterByAsciiCode(code){
    return isLowerByAsciiCode(code) || isUpperByAsciiCode(code);
}

function flipLetter (str){
    let newStr = '';
    for (i of str) {
        const asciiCode = i.charCodeAt();
        if(isLetterByAsciiCode(asciiCode)){
            newStr += String.fromCharCode(asciiCode ^ 32);
        }else{
            newStr += i;
        }
    }
    return newStr;
}

flipLetter('adASjOdapASJO!@#4123123.l124');
// 'ADasJoDAPasjo!@#4123123.L124'
忘年祭陌 2022-05-04 13:56:24
function convertString(str){
    let newStr = '';
    for (i of str){
        /[A-Z]/.test(i) ? newStr+=i.toLowerCase() : newStr+=i.toUpperCase();
    }
    return newStr;
}
console.log(convertString('aSa123,./'));   //AsA123,./
冬天旳、寂寞 2022-05-04 13:56:23

const str = 'AjklAJIBNiuh';
console.log(str)

let newStr = ''
for (const i of str) {
  let j = '';
  if (/[A-Z]/.test(i)) {
   j =  i.toLowerCase();
   
  } else {
   j = i.toUpperCase();
   
  }
  newStr+=j
}
console.log(newStr)
囍笑 2022-05-04 13:56:23

不用转成数组直接replace操作字符串

function transfer(str) {
  return str.replace(/[a-zA-Z]/g, match => {
    return /[a-z]/.test(match) ? match.toUpperCase() : match.toLowerCase()
  })
}
牵你手 2022-05-04 13:56:23
function transString(str) {
  if(typeof str !== 'string') return
  let strArr = str.split('')
  return strArr.reduce((acc, cur) => acc += (cur === cur.toUpperCase() ? cur.toLowerCase() : cur.toUpperCase()))
}
以歌曲疗慰 2022-05-04 13:56:22

let a = 'aB1cd';

const gap = 'a'.charCodeAt() - 'A'.charCodeAt();
const A_ASCII = 'A'.charCodeAt();
const Z_ASCII = 'Z'.charCodeAt();

const test = (a) => a.replace(/[a-zA-Z]/g, (str, value) => {
let ascii_code = str.charCodeAt();
if(ascii_code >= A_ASCII && ascii_code <= Z_ASCII){ //大写
return String.fromCharCode(ascii_code + gap) //转小写
}else{
return String.fromCharCode(ascii_code - gap);
}
})

console.error(test(a));

情独悲 2022-05-04 13:56:22

正则实现:
str.replace(/(w)/g, m => m === m.toUpperCase() ? m.toLowerCase() : m.toUpperCase())

莫言歌 2022-05-04 13:56:21
fn=(str)=>str.replace(/[A-Za-z]/g,c=>String.fromCharCode(c.charCodeAt()+(c<'['?32:-32)))
fn('-@A[Bc')//"-@a[bC"
愚人国度 2022-05-04 13:56:21

用了3种实现方法处理千万级别长度字符,对比了下时间,分享给大家,for循环+unicode转行相对较快
function getRandomStr() {
let str = ''
let arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z"
]
for (let i = 0; i < 10000000; i++) {
let num = parseInt(Math.random() * 53)
str += arr[num]
}
return str
}

    function transformStr1() {
        console.time('生成1千万长度字符串用时')
        let str = getRandomStr()
        console.timeEnd('生成1千万长度字符串用时')
        // console.log(str)
        console.time('使用正则替换用时')
        let str1 = str.replace(/./g, (input) => {
            let num = input.charCodeAt(0)
            if (num >= 65 && num <= 90) {
                return String.fromCharCode(num + 32)
            } else {
                return String.fromCharCode(num - 32)
            }
        })
        console.timeEnd('使用正则替换用时')
        // console.log(str)
        console.time('使用for循环耗时')
        let str2 = ''
        for (let i = 0, len = str.length; i < len; i++) {
            let s = str[i]
            let num = s.charCodeAt(0)
            if (num >= 65 && num <= 90) {
                str2 += String.fromCharCode(num + 32)
            } else {
                str2 += String.fromCharCode(num - 32)
            }
        }
        console.timeEnd('使用for循环耗时')
        console.log(str1 === str2)
        console.time('使用toUppercase逐个转换耗时')
        let str3 = ''
        for (let i = 0, len = str.length; i < len; i++) {
            let s = str[i]
            let sUp = s.toUpperCase()
            if (sUp === s) {
                str3 += s.toLocaleLowerCase()
            } else {
                str3 += sUp
            }
        }
        console.timeEnd('使用toUppercase逐个转换耗时')
        console.log(str2 === str3)
        console.time('使用toUppercase转换字符')
    }
温暖的光 2022-05-04 13:56:17
const reverse = str => {
        let result = ''
	for (let i = 0; i < str.length; i++) {
		if (str[i] > 'Z') {
			result += str[i].toUpperCase()
		} else {
			result += str[i].toLowerCase()
		}
	}
	return result
}
-柠檬树下少年和吉他 2022-05-04 13:56:06

用ASCII做了一下。

// 第 69 题: 如何把一个字符串的大小写取反(大写变小写小写变大写),例如 ’AbC' 变成 'aBc' 。
const reverseStr = (str) => {
  let tmpAry = str.split('')
  let resultAry = []
  let a = 'a'.charCodeAt()
  let A = 'A'.charCodeAt()
  tmpAry.map((val) => {
    // debugger
    if (val <= 'Z' && val >= 'A') {
      resultAry.push(String.fromCharCode(val.charCodeAt() + (a - A)))
    } else if (val <= 'z' && val >= 'a') {
      resultAry.push(String.fromCharCode(val.charCodeAt() - (a - A)))
    } else {
      resultAry.push(val)
    }
  })
  return resultAry.join('')
}
console.log(reverseStr('aBCDefgh!@##%^$^*!@#$%'))
跨年。 2022-05-04 13:56:06
[].map.call(str, function(item){     
     return /[a-z]/.test(item) ? item.toUpperCase() : item.toLowerCase(); 
}).join('');
荒﹫人说梦﹌ 2022-05-04 13:54:55

'AbcDefGh'.replace(/[a-zA-Z]/g,function(a){ return /[a-z]/.test(a)?a.toUpperCase():a.toLowerCase(); });

苦妄 2022-05-04 13:53:26
var str = 'AsdfsCsdefsd,$qwsDR'
var mapCode = {
    'A': 'A'.charCodeAt(0),
    'Z': 'Z'.charCodeAt(0),
    'a': 'a'.charCodeAt(0),
    'z': 'z'.charCodeAt(0),
}
var diff = mapCode.a - mapCode.A
var arr = str.split('')
for(var i = 0; i < arr.length; i++) {
    var code = arr[i].charCodeAt(0)
    if(code >= mapCode.A && code <= mapCode.Z) { // 大写
        arr[i] = String.fromCharCode(code + diff) // 转小写
    }else if(code >= mapCode.a && code <= mapCode.z){ // 小写
        arr[i] = String.fromCharCode(code - diff) // 转大写
    }else { // 不是字母
        console.log(arr[i], "不是字母")
        arr.splice(i, 1)
        i--
    }
}
console.log(arr.join(''))

欢你一世 2022-05-04 13:51:37

@iotale
你这个只考虑了字母,如果有其他字符就行不通了

transStr('adASjOdapASJO!@#4123123.l124')
// "ADasJoDAPasjoA`CTQRSQRSNLQRT"
╮执着的年纪 2022-05-04 13:49:40

马上想到的也是一楼的方法,另外也可以:

function swapString(str) {
  var result = ''

  for (var i = 0; i < str.length; i++) {
    var c = str[i]

    if (c === c.toUpperCase()) {
      result += c.toLowerCase()
    } else {
      result += c.toUpperCase()
    }
  }

  return result
}

swapString('ADasfads123!@$!@#') // => 'adASFADS123!@$!@#'
萌酱 2022-05-04 10:05:21

有没有想到用ascii码的?

const STEP = 'a'.charCodeAt() - 'A'.charCodeAt();

function transCase(char) {
  const asciiCode = char.charCodeAt();
  const resultCode = asciiCode < 'a'.charCodeAt() ? asciiCode + STEP : asciiCode - STEP;
  return String.fromCharCode(resultCode);
}

function transStr(str) {
  const charArr = str.split('');
  return charArr.map(char => transCase(char)).join('');
}

问题是只适用于大小写字母区间,不然表现会很怪异。

优化的时候可以做做边界条件。思路应该没问题。

~没有更多了~

关于作者

绝不放开

暂无简介

0 文章
0 评论
23 人气
更多

推荐作者

已经忘了多久

文章 0 评论 0

15867725375

文章 0 评论 0

LonelySnow

文章 0 评论 0

走过海棠暮

文章 0 评论 0

轻许诺言

文章 0 评论 0

信馬由缰

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文