As the title says, i need to make a function that would make every second word in a sentence uppercase, but do not touch other words. I have this function : (The first if is in a case there is only one word)
And it does its job, however with a sentence like this "ThIs iS A seNteNCe" it returns "this IS a SENTENCE", whereas i need "ThIs IS a SENTENCE".
function largeLetters(sentence) {
return sentence.map((v, i) => i % 2 == 0 ? v.toLowerCase() : v.toUpperCase()).join(' ');
}
function sentenceToUpperCase(sentence) {
sentence = sentence.split(' ');
if (sentence.length == 1) {
sentence = sentence.toString().toUpperCase();
return sentence;
} else {
return largeLetters(sentence)
};
};
console.log(sentenceToUpperCase("ThIs iS A seNteNCe"))
I've simplified your program a bit.
The problem was in this part:
i % 2 == 0 ? word.toLowerCase() : word.toUpperCase()
you don't need to change every other word to lowercase, you just leave it as it is:
i % 2 == 0 ? word : word.toUpperCase()
function sentenceToUpperCase(sentence) {
return sentence
.split(' ')
.map((word, i) => i % 2 == 0 ? word : word.toUpperCase())
.join(' ');
};
console.log(sentenceToUpperCase("ThIs"))
console.log(sentenceToUpperCase("ThIs iS"))
console.log(sentenceToUpperCase("ThIs iS A"))
console.log(sentenceToUpperCase("ThIs iS A seNteNCe"))
When you say
that would make every second word in a sentence uppercase
If you mean 'even value' so use value % 2 === 0 else just change the 2nd value of your array.
Update even words :
function sentenceToUpperCase(sentence) {
const words = sentence.split(' ');
if(words.length >= 2) {
return words.map((v,i) => i % 2 === 0 ? v : v.toUpperCase()).join(' ');
} else {
return sentence.toUpperCase();
}
}
Only update 2nd word :
function sentenceToUpperCase(sentence) {
const words = sentence.split(' ');
if(words.length >= 2) {
words[1] = words[1].toUpperCase();
} else {
return sentence.toUpperCase();
}
return words.join(' ');
}
You can 'minify' it by using a ternary and map
function sentenceToUpperCaseMinify(sentence) {
const words = sentence.split(' ');
return words.length >= 2 ? words.map((v, i) => i === 1 ? v.toUpperCase() : v).join(' ') : sentence.toUpperCase();
}
Cool question and in JS you have many ways to do that. The functions I have used are: lowercase, split, toUpperCase, join. I wrapped in a function.
const str = "this IS a SENTENCE"
function build(str) {
const s = str.split(' ');
// or use (str.toLowerCase()).split(' ') if every odd word have to be lowercase
let r = [];
let i = 0;
s.forEach((e) => {
if (i % 2 === 0) {
r.push(e)
} else {
r.push(e.toUpperCase())
}
i++;
})
return r.join(' ');
}
console.log('new Sentense: ', build(str) );