What is the meaning of regular expression / (hi)? / g?

what is the meaning of the following regular expression?

() is the capture group

? Content that appears 0 or 1 times

but why do they match to two values?

var re = /(hi)?/g;
console.log(re.exec("hi"));  // ["hi", "hi"]

add? Are you in or out? The difference:

null:
r=/(a)/g
r.exec("www")   // null

?:
r=/(a)?/g
r.exec("www")  // ["", undefined, index: 0, input: "www", groups: undefined]

?:
r=/a?/g
r.exec("www")  // ["", index: 0, input: "www", groups: undefined]


r=/,{0}/g
r.exec("www")  // ["", index: 0, input: "www", groups: undefined]

Why is it always successful to match zero times?

Apr.01,2022

< H1 > first question < / H1 >

regexObj.exec (str) in the returned result, the array [0] represents the regular matching character, and the array [1matches n] represents the matching group (matching content in parentheses)

.

change this example to better understand

clipboard.png

regexObj.exec(str)

? 0 1 /(a)?/g /a?/g 0 1 awww

regexp

Menu