Why is the regular expression with type * not working?

This is my code:

const test = "caaaaandy";
const testRegex = /a*/;
const result = test.match(testRegex);

console.log(result);

Output:

[ '', index: 0, input: 'caaaaandy', groups: undefined ]

Why its not this output?

[ 'aaaaa', index: 1, input: 'caaaaandy', groups: undefined ]

Because the description of the * type is :
Matches the preceding item “x” 0 or more times.

Source: Quantifiers - JavaScript | MDN

And my understanding is, that the a is more than zero times there :smiley:

When i change the regex to aa* its working. (i know also a+ is working, but i want to specifically wrong with the * type.)

/a*/

You are telling it to match zero or more times, so it is matching zero times because there are other characters before the first a in the string which allows it to make the zero match. If you want to pull the string of a's out of there then you need to use the + so it matches one or more a's.

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.