Help understanding this regex

Tell us what’s happening:
Hi!
I don’t understand why is it that in the newEnding variable I get the returned value of two “gl” instead of just one. This is messing my code :frowning:

Your code so far


function translatePigLatin(str) {
let vowels = /(^[aeiou])/;
let consonants = /(^[bcdfghjklmnpqrstvwxyz]+)/;
let newEnding = str.match(consonants);
console.log(newEnding)// [ 'gl', 'gl', index: 0, input: 'glove', groups: undefined ]
}

translatePigLatin("glove");


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0.

Challenge: Pig Latin

Link to the challenge:

The + in your consonants regex means that it will match “one or more” sequential consonants at the beginning of the string. Regular expressions are greedy.

1 Like

Yes, but my argument is this:

There is no repeated consonants besides the initial “gl”.

lol…Ariel beat me to it! One additional piece of advice I have, using https://regexr.com/ can be very helpful when doing ANYTHING with regex. It gives great explanations of what the regex is doing, allows you to test the regex, and provides a decent reference you can use to help build them.

1 Like

right…the + in your consonants is what’s causing the problem though. It matches “one or more of the preceding tokens” there is a quantifier that better fits what you need…

I still don’t understand, because if I delete + it still returns the consonant two times:

function translatePigLatin(str) {

let consonants = /(^[bcdfghjklmnpqrstvwxyz])/;

let newEnding = str.match(consonants);

console.log(newEnding)// [ 'g', 'g', index: 0, input: 'glove', groups: undefined ]

}

translatePigLatin("glove");

It doesn’t have to be the same consonant repeated. It’s the pattern (consonants). ‘g’ and ‘l’ are both consonants.

The first one is your complete match and the second one is the capture group.
Take a look at the documentation for .match() and what it returns.

1 Like