问题
I need to make a function that reads a string input and converts the odd indexed characters in the string to upperCase and the even ones to lowerCase.
function alternativeCase(string){
for(var i = 0; i < string.length; i++){
if (i % 2 != 0) {
string[i].toUpperCase();
}
else {
string[i].toLowerCase();
}
}
return string;
}
How to fix my code?
回答1:
Try this:
function alternativeCase(string){
var output = "";
for(var i = 0; i < string.length; i++){
if (i % 2 != 0) {
output += string[i].toUpperCase();
}
else {
output += string[i].toLowerCase();
}
}
return output;
}
回答2:
function alternativeCase(string){
return string.split('').map(function(c,i) {
return i & 1 ? c.toUpperCase() : c.toLowerCase();
}).join('');
}
回答3:
Strings in JavaScript are immutable, Try this instead:
function alternativeCase(string){
var newString = [];
for(var i = 0; i < string.length; i++){
if (i % 2 != 0) {
newString[i] = string[i].toUpperCase();
}
else {
newString[i] = string[i].toLowerCase();
}
}
return newString.join('');
}
回答4:
RegExp alternative that handles space between characters :
const alternativeCase = s => s.replace(/(\S\s*)(\S?)/g, (m, a, b) => a.toUpperCase() + b.toLowerCase());
console.log( alternativeCase('alternative Case') )
来源:https://stackoverflow.com/questions/41452847/converting-odd-and-even-indexed-characters-in-a-string-to-uppercase-lowercase-in