Why does String.match( / \d*/ ) return an empty string?

Remember that match is looking for the first substring it can find that matches the given regex.

* means that there may be zero or more of something, so \d* means you’re looking for a string that contains zero or more digits.

If your input string started with a number, that entire number would be matched.

"5 to 100".match(/\d*/); // "5"
"5 to 100".match(/\d+/); // "5"

But since the first character is a non-digit, match() figures that the beginning of the string (with no characters) matches the regex.

Since your string doesn’t begin with any digits, an empty string is the first substring of your input which matches that regex.

Leave a Comment