HackerRank 10 Days of Javascript: Day 2: loops
2 min readFeb 10, 2021
Task:
Complete the vowelsAndConsonants function in the editor below. It has one parameter, a string, , consisting of lowercase English alphabetic letters (i.e., a
through z
). The function must do the following:
- First, print each vowel in on a new line. The English vowels are a, e, i, o, and u, and each vowel must be printed in the same order as it appeared in .
- Second, print each consonant (i.e., non-vowel) in on a new line in the same order as it appeared in .
Sample Input:
javascriptloops
Sample Output:
a
a
i
o
o
j
v
s
c
r
p
t
l
p
s
My Code:
- I am using Regex to remove the vowels and consonants from the string.
- regex = /[aeiou]/gi is used to remove all the vowels from the string.
- In the regex above i is a flag that means ‘ignore’, I used this to avoid the lowercase and uppercase problems.
- regex = /[^aeiou]/gi is used to remove all the consonants from the string.
- ^ means negating the character set.
function vowelsAndConsonants(s) {let str = '';var v = s.replace(/[^aeiou]/gi, '');str += v;var c = s.replace(/[aeiou]/gi, '');str += c;for (var i of str) {console.log(i);}}
We can optimize this code :
function vowelsAndConsonants(s) {
let str = s.replace(/[^aeiou]/gi, '') + s.replace(/[aeiou]/gi, '');for (var i of str) {console.log(i);}}
Thank you for reading!