I'm confused about between + character and * character (on regular Expression)

the codes below will print[‘CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC’ ]

let criminals = "P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3";
let reCriminals = /c+/gi; 
let result = criminals.match(reCriminals)
console.log(result)

the codes below will print : [’ ', ’ ', ‘CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC’, ’ ’ , ’ ’ ]

let criminals = "P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3";
let reCriminals = /c*/gi; // Change this line
let result = criminals.match(reCriminals)
console.log(result)

so the difference of those (catch criminal challenge) are:
if we use * character it will print with space, but if we use + character it will not print with space

my question: why with the * character it will print with the space? so that’s why I’m still confused between * character and + character

If you don’t give any parameter and use the match() method directly, you will get an Array with an empty string: [""]. MDN Source

It seems your /c*/gi is reduced to nothing when there is no c, so it’s the same than passing match(), then because it’s iterative, you get all those empty values.

Now, when you pass /c+/gi, you never get any [""] in return, it’s either one or more c characters, or not a match.


Sidenote
You’ll get a lot more understanding just playing with minimal, simple examples, and trying regex on them.

2 Likes

Still can’t understand why using * would return a space if there is a match.

Like mentioned above: Why is this happening?

the codes below will print : [’ ', ’ ', ‘CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC’, ’ ’ , ’ ’ ]