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");

9
  • 3
    What were you expecting? Commented Aug 5, 2020 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. Commented Aug 5, 2020 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. Commented Aug 5, 2020 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. Commented Aug 5, 2020 at 22:41
  • 1
    .match without the g flag on your RegExp returns an Array of the first match followed by parenthetical subpatterns. Commented Aug 5, 2020 at 22:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You should put reg('turtle'); at the end of your snippet so the OP can see the output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.