regex: extract SVG path d attribute

Viewed 707

I have a source containing one SVG path:

<svg xmlns="http://www.w3.org/2000/svg" stroke="red" fill="grey"><path d="M 10 10 L 100 100 Q 200 50 300 100 A 80 50 20 1 0 400 600 Z" fill="none" stroke="red" stroke-width="5" /></svg>

it also can be single quoted

<svg xmlns="http://www.w3.org/2000/svg" stroke="red" fill="grey"><path d='M 10 10 L 100 100 Q 200 50 300 100 A 80 50 20 1 0 400 600 Z' fill="none" stroke="red" stroke-width="5" />

I want the part between <path=start quote and finish quote.

M 10 10 L 100 100 Q 200 50 300 100 A 80 50 20 1 0 400 600 Z

I have tried (JS)

var result = svg_tag.match(/<path(.*?)>/g).map(function(val){
   return val.replace(/<path d="/g,'');
});

But it returns

[
  'M',                '10',
  '10',               'L',
  '100',              '100',
  'Q',                '200',
  '50',               '300',
  '100',              'A',
  '80',               '50',
  '20',               '1',
  '0',                '400',
  '600',              'Z"',
  'fill="none"',      'stroke="red"',
  'stroke-width="5"', '/>'
]
1 Answers

[ \w]{10,}

This RegExp matches any substring at least 10 characters long containing only letters, numbers, spaces, and underscores.

const regex = /[ \w]{10,}/;

const tag1 = '<svg xmlns="http://www.w3.org/2000/svg" stroke="red" fill="grey"><path d="M 10 10 L 100 100 Q 200 50 300 100 A 80 50 20 1 0 400 600 Z" fill="none" stroke="red" stroke-width="5" /></svg>';
const tag2 = `<svg xmlns="http://www.w3.org/2000/svg" stroke="red" fill="grey"><path d='M 10 10 L 100 100 Q 200 50 300 100 A 80 50 20 1 0 400 600 Z' fill="none" stroke="red" stroke-width="5" />`;

console.log(tag1.match(regex)[0]);
console.log(tag2.match(regex)[0]);

Related