字符串字母大小写反转

发布时间 2023-11-15 17:11:49作者: 雪旭

要求:对字符串的字母进行大小写反转,大写字母转为小写,小写字母转为大写。

方法1:使用正则

先对字符串使用split方法转为数组,在对数组进行循环判断看它是否是字母,然后使用toUpperCase转大写,toLowerCase转小写。

const str = 'SDFaskdjhkHJG';
//反转方法
function changeCase(str){
    //大写字母正则
    const capsPattern = /[A-Z]+/;
    //小写字母正则
    const smallPattern = /[a-z]+/;
    const arr = str.split('');
    let newStr = '';
    arr.forEach(item => {
    if(capsPattern.test(item)){
        newStr += item.toLowerCase()
    }else if(smallPattern.test(item)){
        newStr += item.toUpperCase()
    }else{
        newStr += item
    }
    });
    return newStr;
}

方法2:使用ASCII编码

先对字符串使用split方法转为数组,在对数组进行循环,对数组的每一项使用charCodeAt方法用来获取在ASCII编码中的位置。65~90为26个大写英文字母,97~122号为26个小写英文字母。

const str = 'SDFaskdjhkHJG';
//是否是大写
function isUppercase(str) {
    return str.charCodeAt(0) >= 65 && str.charCodeAt(0) <= 90;
}
//是否是小写
function isLowercase(str) {
    return str.charCodeAt(0) >= 97 && str.charCodeAt(0) <= 122;
}
//反转方法
function changeCase(str){
    const arr = str.split('');
    let newStr = '';
    arr.forEach(item => {
    if(isUppercase(item)){
        newStr += item.toLowerCase()
    }else if(isLowercase(item)){
        newStr += item.toUpperCase()
    }else{
        newStr += item
    }
    });
    return newStr;
}