RegEx for consonants

Hello all!

I wrote a basic program in JavaScript which tells you how many vowels and consonants includes your sample text. I didn’t satisfied 4th line in my code. I want to write it with something special like;

everything - [aeiou]

instead of typing

bcdfgh…

I googled a bit but results which I found didn’t worked. I’m waiting for your ideas!
Peace:face_with_hand_over_mouth:

2 Likes

Correct me if I am wrong, but you are wanting a shorter regex than the following for the consonants?

let consonantRegex = /[bcdfghjklmnpqrstvwxys]/gi;
4 Likes

Yes, thats why exactly I want.

But the point isn’t the length of code. For example I just noticed I wrote …wxys… instead of …wxyz.
I am wondering if I wrote that line something like

let consonantRegex = /everywords - [aeiou]/gi;

I am not sure the point of including the “everywords -”, but below are two ways you could accomplish what I stated above.

The first way (below) uses a negative lookahead to match any letter (a-z) which is not a vowel (aeiou).

let vowelRegex = /[aeiou]/gi; // List of vowels (Global and Insensitive)
let consonantRegex = /[(?![aeiou])[a-z]]/gi; // List of consonants (Global and Insensitive)

OR if you want to use a variable for the vowels and dynamically create the regular expression using a template literal, you could do the following.

const vowels = 'aeiou';
let vowelRegex = new RegExp(`[${vowels}]`,'gi'); // List of vowels (Global and Insensitive)
let consonantRegex = new RegExp(`(?![${vowels}])[a-z]`, 'gi'); // List of consonants (Global and Insensitive)
17 Likes