Checking for vowels and consonants in a string and printing them out

I'm doing a challenge on Hackerrank, the task is to check for vowels and consonants in a string and printing both (ordered) in separate lines. I can print out the vowels just fine but can't do the same with consonants. It won't output them. Here's my code:

    const vowels = 'aeiou'
    
    var consonants = []
    for (var i=0;i<s.length;i++) {
        if(vowels.includes(s[i])) {console.log(s[i])
        } 
        else {
            consonants+= s[i] + '\n'
        }
     
    } 
    
}

Upvotes: 1

Views: 626

Answers (2)

Kyuiki
Kyuiki

Reputation: 11

You can use regex and string.match() to split the vowels and consonants. like this

const s = "hello World";
const [vowels, consonants] = [s.match(/[aiueo]/gi), s.match(/[^aiueo\s]/gi)];
vowels.forEach(o => console.log("vowels => "+o))
consonants.forEach(o => console.log("consonants => "+o))

Upvotes: 1

Roh&#236;t J&#237;ndal
Roh&#236;t J&#237;ndal

Reputation: 27202

You can simply achieve that by using regex and string.match() method.

Live Demo :

const str = "Separate the vowels and consonants from a string"; 
const vowels = str.match(/[aeiou]/gi); 
const consonants = str.match(/[^aeiou]/gi); 

console.log(vowels);
console.log(consonants);

Upvotes: 1

Related Questions