js 字符串大小写反转

60 阅读1分钟

1. 使用toUpperCase() 和 toLowerCase() 

function reverseCase(str) { 
    let s = ""; 
    for (let i = 0; i < str.length; i++) { 
        let c = str[i]; 
        if (c === c.toUpperCase()) { 
            s += c.toLowerCase(); 
        } else { 
            s += c.toUpperCase(); } 
        } 
    return s; 
}

2. 使用正则

function reverseCase(str) { 
    return str.replace(/[a-zA-Z]/g, function(s) { 
        return s === s.toUpperCase() ? c.toLowerCase() : c.toUpperCase(); 
    });
}