I've been trying to make that thing work but the output is probably not too far from the expected result - yet still ,not the correct output.
flipCase();
function flipCase() {
var string = prompt("Please enter a string:");
var vowels = "aeiou";
var newString = "";
for (var i = 0; i < string.length; i++) {
for (var j = 0; j < vowels.length; j++) {
if (string.charAt(i) === vowels.charAt(j)) {
newString += string.charAt(i).toUpperCase();
} else {
newString += string.charAt(i).toLowerCase();
}
}
}
console.log(newString);
}
The input is : open.
The output is : oooOopppppeEeeennnnn.
The expected output is : OpEn.
If you found a vowel, you need to leave the inner loop and omit adding the character to the result string.
function flipCase(string) {
string = string || prompt("Please enter a string:");
const vowels = "aeiou";
let newString = "";
for (let i = 0; i < string.length; i++) {
let character = string[i].toLowerCase();
for (let j = 0; j < vowels.length; j++) {
if (character === vowels[j]) {
character = character.toUpperCase();
break;
}
}
newString += character;
}
return newString;
}
console.log(flipCase('open'));
Check the index of each character in the string against against the vowels string using indexOf. This way there's no nested loop.
function flipCase(str) {
const vowels = 'aeiou';
let newString = '';
// Iterate through the string - if the
// (lowercase) character in the current iteration
// is in the vowels string, make it uppercase, and
// add it to `newString`, otherwise just add it
for (var i = 0; i < str.length; i++) {
const char = str[i].toLowerCase();
if (vowels.indexOf(char) > -1) {
newString += char.toUpperCase();
} else {
newString += char;
}
}
return newString;
}
console.log(flipCase('open'));
console.log(flipCase('OPEN'));
console.log(flipCase('OPeN'));
console.log(flipCase('Gah! Homework :)'));
This looks homework-like enough that I'm not going to just give you the full answer, but I'll get you halfway there:
function flipCase() {
var string = "here is some sample input"; // prompt doesn't work in SO snippets in some browsers
var vowels = "aeiou";
var newString = "";
for (var i = 0; i < string.length; i++) {
for (var j = 0; j < vowels.length; j++) {
if (string.charAt(i) === vowels.charAt(j)) {
newString += string.charAt(i).toUpperCase();
}
// the "else" can't go here, or it'll emit once for each
// vowel whether it matches the current character or not.
}
// you need to output consonants outside the 'vowel' loop,
// but this will also emit if the current character is a
// vowel:
newString += string.charAt(i).toLowerCase();
// ...so you'll need to wrap the above in some other
// condition to tell it when not to output. Possibilities
// include checking specifically for not-a-vowel, or
// setting a temporary variable whenever you output a vowel
// that can be read here to prevent outputting it again
}
console.log(newString);
}
flipCase();