Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...