王培顺的博客&WangPeishun’s Blog

字符串字母大小写反向输出
altERnaTIng cAsE <=> ALTerNAtiNG CaSe

这里分享的都是大家比较认可的几个方案:
1.

String.prototype.toAlternatingCase = function () {
return this.split("").map(a =&gt; a === a.toUpperCase()? a.toLowerCase(): a.toUpperCase()).join('')
}

2.

const isLowerCase = (char) =&gt; char.toLowerCase() === char;
const swapCase = (char) =&gt; 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 =&gt; x &gt; "Z" ? x.toUpperCase() : x.toLowerCase())
}

5.

String.prototype.toAlternatingCase = function(){
return this.split("").map(letter =&gt; {
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 =&gt; {
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 &lt; 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 &gt;= 'A' &amp;&amp; x &lt;= 'Z') return x.toLowerCase(); if(x &gt;= 'a' &amp;&amp; x &lt;= 'z') return x.toUpperCase();
return x;
}).join('');
}

9.

String.prototype.toAlternatingCase = function () {
var letter, idx = 0, alt ='';
while (idx &lt; 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 =&gt; 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 &lt; this.length; ++i) {
if(isUpper(this[i])) {
out += this[i].toLowerCase();
}
else {
out += this[i].toUpperCase();
}
}
return out;
}

标签: none

添加新评论