JS小函数-字符串字母大小写反向输出
字符串字母大小写反向输出
altERnaTIng cAsE <=> ALTerNAtiNG CaSe
这里分享的都是大家比较认可的几个方案:
1.
String.prototype.toAlternatingCase = function () {
return this.split("").map(a => a === a.toUpperCase()? a.toLowerCase(): a.toUpperCase()).join('')
}
2.
const isLowerCase = (char) => char.toLowerCase() === char;
const swapCase = (char) => isLowerCase(char) ? char.toUpperCase() : char.toLowerCase();
String.prototype.toAlternatingCase = function() {
return [...this].map(swapCase).join('');
};
3.
String.prototype.toAlternatingCase = function () {
return this.replace(/./g, function (match) {
return /[a-z]/.test(match) ? match.toUpperCase() : match.toLowerCase();
});
}
4.
String.prototype.toAlternatingCase = function () {
return this.replace(/[A-Za-z]/g, x => x > "Z" ? x.toUpperCase() : x.toLowerCase())
}
5.
String.prototype.toAlternatingCase = function(){
return this.split("").map(letter => {
var newLetter = letter.toUpperCase();
return letter == newLetter ? letter.toLowerCase() : newLetter;
}).join("");
}
6.
String.prototype.toAlternatingCase = function () {
return this.replace(/[a-zA-Z]/g, function (ltr) {
return ltr === ltr.toUpperCase() ? ltr.toLowerCase() : ltr.toUpperCase();
});
};
7.
String.prototype.toAlternatingCase = function () {
return this.split('').map(i => {
if (/[a-z]/i.test(i)) {
return i.toUpperCase() === i ? i.toLowerCase() : i.toUpperCase();
} else {
return i;
}
}).join('');
}
8.
String.prototype.toAlternatingCase = function () {
new_str = "";
for(var i = 0; i < this.length; i++) { if(this[i] === this[i].toUpperCase()) { new_str += this[i].toLowerCase(); } else { new_str += this[i].toUpperCase(); } } return new_str; } [/code] [code] String.prototype.toAlternatingCase = function () { return this.split('').map(function(x){ if(x >= 'A' && x <= 'Z') return x.toLowerCase(); if(x >= 'a' && x <= 'z') return x.toUpperCase();
return x;
}).join('');
}
9.
String.prototype.toAlternatingCase = function () {
var letter, idx = 0, alt ='';
while (idx < this.length) { letter = this[idx]; if (letter === letter.toUpperCase()) { alt += letter.toLowerCase(); } else { alt += letter.toUpperCase(); } idx++; } return alt; }; [/code] [code] String.prototype.toAlternatingCase = function () { return this.split('').map(char => char === char.toUpperCase() ? char.toLowerCase() : char.toUpperCase()).join('');
}
10.
String.prototype.toAlternatingCase = function () {
let isUpper = function(c) {
if(c === c.toUpperCase()) return true;
return false;
};
let out = '';
for(let i = 0; i < this.length; ++i) {
if(isUpper(this[i])) {
out += this[i].toLowerCase();
}
else {
out += this[i].toUpperCase();
}
}
return out;
}