Hi Friends 👋,
Welcome To Infinitbility! ❤️
To separate vowels and consonants in a string in javascript, use the match()
method with /[aeiou]/gi
regex it is the simplest way to separate vowels and consonants from a string.
Today, I’m going to show you How do I separate vowels and consonants in a string in javascript, as mentioned above, I’m going to create a sample string variable with data and use the match()
method with /[aeiou]/gi
regex to separate vowels and consonants.
Let’s start today’s tutorial on how do you separate vowels and consonants in a string in javascript.
Javascript separates vowels and consonants in a string
Here, we will do
- Create a sample string variable
- Separate vowels from a string
- Make vowels array into comma separate string
- Remove commas from comma-separate vowels
- Separate consonants from string
- Make consonants array into comma separate string
- Remove commas from comma-separate consonants
// Create a sample string variable
const str = "infinitbility";
// Separate vowels from string
const vowels = str.match(/[aeiou]/gi);
console.log("vowels :", vowels)
// vowels : [ 'i', 'i', 'i', 'i', 'i' ]
// Make vowels array into comma separate string
console.log("vowels as string:", vowels.join())
// vowels as string: i,i,i,i,i
// Remove commas from comma separate vowels
console.log("vowels as string without comma:", vowels.join().replace(/[,]/g, ""))
// vowels as string without comma: iiiii
// Separate consonants from string
const consonants = str.match(/[^aeiou]/gi);
console.log("consonants :", consonants)
// consonants : [
// 'n', 'f', 'n',
// 't', 'b', 'l',
// 't', 'y'
// ]
// Make consonants array into comma separate string
console.log("consonants as string:", consonants.join())
// consonants as string: n,f,n,t,b,l,t,y
// Remove commas from comma separate consonants
console.log("consonants as string without comma:", consonants.join().replace(/[,]/g, ""))
// consonants as string without comma: nfntblty
Output
I hope it helps you, All the best 👍.