Regular expressions: character class vs OR operator

The challenge Regular Expressions: Match Single Character with Multiple Possibilities made me wonder: is there any difference between using the alteration, or OR operator, between each letter of aeiou and putting aeiou in a character class as called for in the challenge? I’m pretty sure the following would produce the same result (though it doesn’t pass that challenge because a character class is not used) but want to be sure.

let quoteSample = "Beware of bugs in the above code; I have only proved it correct, not tried it.";
let vowelRegex = /a|e|i|o|u/ig; // Change this line
let result = quoteSample.match(vowelRegex); // Change this line

This wouldn’t pass the challenge, where is the string you need to use the method on?

I don’t know about class and OR, tho

Oops, I had put let result = vowelRegex.match(vowelRegex); instead of let result = quoteSample.match(vowelRegex);. After fixing I was able to confirm the character class and OR have the same result.

They do essentially the same thing for single characters. However, you can also use the OR operator for groups of characters:

const friends = /Frankie|Mel|Kris/;

friends.test('Mel'); // true
friends.test('Andie'); // false

You can’t do this with character classes, but character classes are handy because they’re a more concise syntax if you’re dealing with single characters. You can think of it as syntactic sugar.

Some characters are also interpreted differently within character classes:

const first = /./; // matches any character
const second = /[.]/; // matches a literal period
const third = /\./; // same as second, due to being backslash escaped
2 Likes

Thanks for your insight!