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'
}
}
}
CodePudding user response:
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);
CodePudding user response:
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))