简体   繁体   中英

regex: extract SVG path d attribute

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"', '/>'
]

[ \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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM