Difference between + and * on RegExp

Tell us what’s happening:
Hi guys, I’m playing with the code to understand + and * quantifiers. If i’m correct + it’s like writing {1,} and * it’s like writing {0,} after the regex pattern.

I don’t understand why in the second regex assingment it is returned an empty string on the console. Shouldn’t it return [ ‘rrrrr’, index: 1, input: ‘arrrrrg’, groups: undefined ]? Because there are 5 r characters in the variable “word”

Thanks!

Your code so far


let word = "arrrrrg";
let regex = /r{1,}/;
console.log(word.match(regex))
// returns [ 'rrrrr', index: 1, input: 'arrrrrg', groups: undefined ]
regex = /r{0,}/;
console.log(word.match(regex))
//returns [ '', index: 0, input: 'arrrrrg', groups: undefined ]

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36.

Challenge: Match Characters that Occur Zero or More Times

Link to the challenge:

try adding the g flag to the regex and see what are all the substrings matched there

/r{0,}/ match as first thing '' because it matches also 0 r

try adding the g flag to the regex and see what are all the substrings matched there

let word = "arrrrrg";
let regex = /r{0,}/g;
console.log(word.match(regex))
//returns [ '', 'rrrrr', '', '' ] 

1- The first element returns an empty string because the first character of “arrrrrg” it’s not an “r”?
2- why it now returns 4 elements? what are the two empty strings at the end?
3- why using a g flag changes the returned value from [ 'rrrrr', index: 1, input: 'arrrrrg', groups: undefined ] to [ '', 'rrrrr', '', '' ] ?

/r{0,}/ match as first thing '' because it matches also 0 r

4- it matches 0 because it is comparing it with the 0 index element which is in this case a?

Thank you!

it’s a bit too technical for me, I don’t know regex that much

but the match element with the gflag returns all matches in the string, if you don’t use it you have only first match, and extra infos

Thanks anyway :slight_smile:
Maybe someone who knows more about RegExp can answer my questions.