Shouldn't it be /<h.*?1>?

The code following works fine, but I’m confused that where the “h” and “1” come from, and shouldn’t the regexes be" /<h.*?1>"? Anybody can help me with this? Thanks.

The question is as followed:
Fix the regex /<.*>/ to return the HTML tag <h1> and not the text "<h1>Winter is coming</h1>" . Remember the wildcard . in a regular expression matches any character.

and here is the answer:


let text = "<h1>Winter is coming</h1>";
let myRegex = /<.*?>/; // Change this line
let result = text.match(myRegex);

Challenge: Find Characters with Lazy Matching

Link to the challenge:

What are you trying to match with your pattern?
Can you break down each of the characters in the pattern you built (h.*?1>) for me and explain why you added each one?

1 Like

Sorry, I forgot to post the question:
Fix the regex /<.*>/ to return the HTML tag <h1> and not the text "<h1>Winter is coming</h1>" . Remember the wildcard . in a regular expression matches any character.

I believe that either <.*?> or <h.*?1> will meet that requirement. It’s worth noting though that there aren’t valid html tags where there would be characters between the “h” and the “1”, so if your goal is to make the pattern more specific (and only match opening h1 tags and no others), then it would make more sense to do <h1.*?> because that would allow for matching things like <h1 class="myHeader" id="myHeaderId"> etc.

The regex <.*> matches any characters between < and >. The dot . itself means ‘any single character’. The * means zero or more occurrences of the character. So all together, this expression means zero or more occurences of any character (which even includes h and 1), lying between < and >. But by default regex searches greedy and covers the biggest possible match - which in the greedy case would be <h1 … all the way through…/h1>. But in the lazy case it would look only at the closest possible closing > and not go all the way to the farthest closing >.

1 Like

The last word you said makes sence.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.