0

So, i been getting this kind of output lately when im coding but i just want to make sure its normal or maybe im doing something wrong. Here is a simple code.. maybe it has to do with regex.

my console says " (1) ['a', index: 1, input: 'karina', groups: undefined] "

function reg(s) {
    reg = /[aeiou]/;
    console.log(s.match(reg));
}
reg("turtle");
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Karina Turtle
  • 81
  • 1
  • 9
  • Your input in your example doesn't match your console output. There's not enough information here to know what exactly you're finding to be weird, but everything seems in order besides your example using `turtle` versus `karina`. – Slbox Aug 05 '20 at 22:33
  • 3
    What were you expecting? – Unmitigated Aug 05 '20 at 22:34
  • 1
    It is correct it checks if the string has any matching character to your values of aeiou and the index of the first one and will return null otherwise. – Arundeep Chohan Aug 05 '20 at 22:37
  • 1
    Redefining a function while inside that function will almost never do what you want. Anecdotally I did that once, on purpose, but never ever do that. – Dave Newton Aug 05 '20 at 22:39
  • 2
    If you use `reg("turtle");` and then get `['a', index: 1, input: 'karina'` you have an issue but you are not showing the right code. – Wiktor Stribiżew Aug 05 '20 at 22:41
  • See https://stackoverflow.com/questions/56392943/why-the-additional-properties-of-stringmatch-regexpexec-are-not-in-the-ret – Bergi Aug 05 '20 at 22:51
  • 1
    `.match` without the `g` flag on your RegExp returns an Array of the first match followed by parenthetical subpatterns. – StackSlave Aug 05 '20 at 22:58
  • sorry guys. I didnt wait it to show "karina" so i changed it to "turtle" the input should also be "turtle" @WiktorStribiżew – Karina Turtle Aug 05 '20 at 23:02
  • Then edit the question. – Robo Robok Aug 05 '20 at 23:09

1 Answers1

1

Your code is working just fine. The .match() method will compare the string and the RegEx that you defined and return an array with the first match it finds and at what index it happens.

If you want to get back an array with all of the results and without the other information, all you need to do is add a "g" at the end of your RegEx. Your function should look like this:

function reg(s) {
    reg = /[aeiou]/g;
    console.log(s.match(reg));
}

reg('turtle');

The "g" at the end, will make so that .match() will look and grab all of the occurrences in the string that you are checking, instead of just the first one.

J.Felipe
  • 60
  • 1
  • 2
  • 9