Home > database >  homework assignment function given a string, loop through and console.log() only the vowels. I'
homework assignment function given a string, loop through and console.log() only the vowels. I'

Time:10-21

I have a function takes a string and logs only the vowels of this string. Currently each vowel is logged on a new line and that is no good.

function vowelsOnly(str) {
    let vowels = ['a','e','i','o','u']; 
    for (let i = 0; i < str.length; i  ) {
        if (vowels.indexOf(str[i]) > -1 ) {
            // newstr convert to string
            let newstr = str[i].toString();
            console.log(newstr);
        }
        // if no vowels in str log empty string
        else {
            console.log("");
        }
    }
}

I need assistance making my code replicate this example: Input is "welcome to my world" expected output is "eoeoo" no commas.

Thank you for your time.

EDIT this code is working for me.

const str = "qqwwrrttppssddaeu"
const vowels = str => str.split('').filter(i=>"aeiou".split('').includes(i)).join('');
let newstr = vowels(str).length;
if (newstr > 1){
    console.log(vowels(str));
}
else {
  console.log("");
}

CodePudding user response:

Have a look at string iterators to iterate over string.

Obviously the input needs to be processed to generate the result which goes to console.log. The effective tool to do it would be Array.prototype.filter which iterates the array implicitly. The array could be obtained by String.prototype.split. To put it together, the algorithm can be expressed as

const vowels = str => str.split('').filter(i=>"aeiou".includes(i)).join('');

So you can get the result by calling

console.log(vowels("welcome to my world"))

Enjoy functional javascript.

CodePudding user response:

Store all vowels in an array. Then join the array and return it

const str = 'asdrqwfsdgobopwkodvcxvuqbe'

console.log(vowelsOnly(str))

function vowelsOnly(str) {
  const result = []
  let vowels = ['a', 'e', 'i', 'o', 'u'];
  for (let i = 0; i < str.length; i  ) {
    if (vowels.indexOf(str[i]) > -1) {
      result.push(str[i])
    }
  }
  return result.join('')
}

one-liner

const str = 'asdrqwfsdgobopwkodvcxvuqbe'

console.log(str.match(/[aeiou]/g).join(''))

  • Related