Ask for advice! The master explains why the regular expression of this js matches two empty strings.

clipboard.png

Apr.14,2021

first, that is not an empty string
second, parentheses denote "capture" in the regular, such as '123abc'.replace (/ (\ d +) abc/,' $1') where $1 indicates the matching content in the first parenthesis, that is, 123 .
third, in this case, to clarify the problem, change to 'a'.match (/ () a /) , and the result will be ["a", ", index: 0, input:" a ", groups: undefined] . The first element in the result is all the strings matched by the regular expression () a , and the second element is the result of the first" capture " () . This means word boundary , which is equivalent to \ b in regular expressions.

back to the topic, the writing in the title is equivalent to '.match (/ (\ b) /) . Since the body of the regular expression is only captured, the first element in the result is the same as the second element, which looks like an "empty string" but is actually not "empty". Please compare with the third point to understand.

Menu