Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex matching <SVG> tags with optional attribute viewBox

I'm trying to match <svg> tag with optional attribute viewBox and to extract its value. I want to match all of the following variations of <svg> tag:

<svg width="28" height="32" viewBox="0 0 28 32">
<!-- svg content must be grouped -->
</svg>


<svg viewBox="0 0 28 32">
<!-- svg content must be grouped -->
</svg>

<svg width="28" height="32" viewBox="0 0 28 32">
<!-- svg content must be grouped -->
</svg>

<svg>
<!-- svg content must be grouped -->
</svg>

<svg viewBox="0 0 28 32" width="28" height="32">
<!-- svg content must be grouped -->
</svg>

here, width and height and viewBox are optionals and value of viewBox attribute and svg content must be grouped.

the following regex works in case that viewBox is required attribute:

/<svg\b[^>]*\s*(viewBox=\"(\b[^"]*)\").*?>([\s\S]*?)<\/svg>/

please see demo

enter image description here

but when I make viewBox optional group, there is no matched group (note ? symbol after parentheses):

/<svg\b[^>]*\s*(viewBox=\"(\b[^"]*)\")?.*?>([\s\S]*?)<\/svg>/

enter image description here

like image 379
SKMohammadi Avatar asked Jun 09 '26 08:06

SKMohammadi


1 Answers

At end it solved by following regex:

<svg\b[^>]*?(?:viewBox=\"(\b[^"]*)\")?>([\s\S]*?)<\/svg>

Demo

like image 98
SKMohammadi Avatar answered Jun 11 '26 22:06

SKMohammadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!