* and + behaving differently in regex

Viewed 72
"ange134".match(/\d+/)       // result =>  134
"ange134".match(/\d*/)       // result =>  ""     //expected 134

In the above cases, + behaves okay, by being greedy.

But why is /\d*/ not returning the same thing?

3 Answers
"ange134".match(/\d+/)       // result =>  123

In the above case \d+ makes sure that there has got to be at least one digit which may be followed by more, thus when the scanning begins and it finds "a" at the beginning it still keeps searching for digits as the condition is not met.

"ange134".match(/\d*/)       // result =>  ""     //expected 123

However in the above case, \d* implies that zero or more occurrence of digit. So when the scanning begins and when it finds "a" the condition is met (which is zero occurrence of digit)... therefore you are getting empty result set.

You may put global flag /g to make it keep searching for all result. See this link to understand how the behavior changes with global flag. Try to turn it on and off to understand it better.

console.log("ange134".match(/\d*/));
console.log("ange134".match(/\d*$/));
console.log("ange134".match(/\d*/g));
console.log("134ange".match(/\d*/));   // this will return 134 as that is the first match that it gets

"ange134".match(/\d*/);

Means "match a number character 0 or more times". As Ryan pointed out above, an empty string satisfies this regex. Try:

"ange134".match(/\d*$/);

and you can see that it does in fact work - just needs some context if your goal is to match the 134 part of that string.

"ange134".match(/\d*/) //means 0 or more times, and this match in the first
//letter (because it "returns false") because you aren't using global flag that search in the whole string

if you want it to work then use global flag:

"ange134".match(/\d*/g)

or use your first correct option without a flag:

"ange134".match(/\d+/)

in this link there is an explanation of why it match the first "a" letter: https://regex101.com/r/3ItllY/1/

Related