Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

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

Can someone help me to understand why using d* returns an array containing an empty string, whereas using d+ returns ["100"] (as expected). I get why the d+ works, but don't see why exactly d* doesn't work. Does using the * cause it to return a zero-length match, and how exactly does this work?

var str = 'one to 100';
var regex = /d*/;
console.log(str.match(regex));
// [""]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...