CodexBloom - Programming Q&A Platform

Regex Not Capturing Multiple Occurrences of HTML Tags in JavaScript

๐Ÿ‘€ Views: 1306 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-12
regex javascript html JavaScript

I'm trying to extract all occurrences of specific HTML tags (like `<div>` and `<span>`) from a block of HTML using a regex in JavaScript. My current regex seems to only capture the first occurrence of the tags, which is not what I intended. Hereโ€™s the regex Iโ€™m using: ```javascript const htmlString = '<div>Hello</div><span>World</span><div>Another div</div>'; const regex = /<div>(.*?)</div>|<span>(.*?)</span>/g; const matches = htmlString.match(regex); console.log(matches); ``` When I run this code, I only get an array containing the first `<div>` and the first `<span>`: ``` [ '<div>Hello</div>', '<span>World</span>' ] ``` I expected it to give me all `<div>` and `<span>` elements, like: ``` [ '<div>Hello</div>', '<span>World</span>', '<div>Another div</div>' ] ``` Iโ€™ve tried modifying the regex to include global flags and lookaheads, but Iโ€™m still exploring. Iโ€™m working with Node.js v16.0.0, so I thought regex would handle this properly, but it seems like I'm missing something essential. Any suggestions on how I can adjust my regex to capture all occurrences?