tonymx227 tonymx227 - 7 months ago 116
Javascript Question

Extract svg path with regex

I want to extract the SVG path using regex and javascript, but it doesn't work.

My SVG file :

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" viewbox="0 0 100 100">
<path d="M0.675,11.333h98.849v21.182H0.675V11.333z M0.675,39.576h98.849v21.183H0.675V39.576z M0.675,67.818h98.849v21.184H0.675
V67.818z"/>
</svg>


My regex :
/^<path(.*)\/>$/gm


I'd like to get this :
<path d="M0.675,11.333h98.849v21.182H0.675V11.333z M0.675,39.576h98.849v21.183H0.675V39.576z M0.675,67.818h98.849v21.184H0.675
V67.818z"/>


And I get no results...

Answer

Dot in js regex won't match line breaks.

var s = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" viewbox="0 0 100 100">\n<path d="M0.675,11.333h98.849v21.182H0.675V11.333z M0.675,39.576h98.849v21.183H0.675V39.576z M0.675,67.818h98.849v21.184H0.675\nV67.818z"/>\n</svg>';
alert(s.match(/<path\b([\s\S]*?)\/>/g))

[\s\S]* matches any character including line breaks.