Positioning the ? character in lazing matching

Just a little something that I am having trouble understanding.

I took the example from the instructions to codepen.io so I could mess around with it a bit to make sure I was grasping the concept properly of the ? character when lazy matching.

I began moving around the ? character to see what would happen and when I moved it to the end of the regex I thought there would be no difference in the match, but instead it returned “titanic” rather than “titani” .

I can only assume that the ? character stops after matching the character behind it ?

let ship = "titanic"; 

let regex = /t[a-z]*i?/;  // why does this return "titanic" instead of just "titani"

let result = ship.match(regex);


Also I might add this came up because my solution to the lesson itself was :

let myRegex = /<h.?1*>/;
//but It also accepted this : 
let myRegex = /<h.1*?>/;

which led me to believe it made no difference where I put the ? character.

depending on where you put it, ? means zero or more characters
for example if you put as /colou?r/ this match both "color" and "colour"

you need to put the ? in front of one of the characters that say how many times to capture something, in that way you would have the lazy effect

this is “t followed by 0 or more [a-z] followed by 0 or 1 i”

this is “open angular bracket followed by h followed by one or zero any character followed by zero or more 1 followed by angular bracket”

this is “open angular bracket followed by any character followed by zero or more (lazy) 1”

the correct ways for this would be


or something like that
this mean “open angular bracket followed by zero or more (lazy) any character followed by closed angular bracket”
here you can see the effect of lazy matching because otherwise it would match until the > of the closing tag

I can understand this, as the angular bracket is specified in the regex.

I am just confused as to why this


would return [titanic] instead of [titani]. since in the lazy match regex the character c is not specified to match. Also from what I have read ? is supposed to return the smallest possible sub string that satisfies the regex pattern.

When using the regex /t[a-z]*i?/ wouldn’t [titani] be the smallest sub string of “titanic” ?

there is no lazy matching there, that mean “t followed by zero or more [a-z] followed by one or zero i”, as it is greedy, it takes the whole string

to have lazy matching you need to put the ? right after a counter like + or *

if you don’t do that, then the ? means “zero or one”

This is what I was not understanding . thank you !