-1

I have this kind of SVG string that comes from a file

<svg>
    <g fill="#767676" />
    <path d="M15.7198 19.5836C15.4" fill="#767676" />
</svg>

And I want to remove every fill attribute from <path> element only so it becomes like this

<svg>
    <g fill="#767676" />
    <path d="M15.7198 19.5836C15.4" />
</svg>

I have tried this regex, but it somehow removes the fill attribute on other elements.

svgString.replace(/(?:<path)*fill=["|'](.*?)["|']\s*/g, '')

This part (?:<path) to exclude the tag element not to be removed but still missing the right way to select only <path /> element and been stuck on this for some time. Hoping someone can show me the right way to do it. Thank you

Dion Dirza
  • 2,575
  • 2
  • 17
  • 21
  • 2
    Should rather not use regex for this to begin with (https://stackoverflow.com/q/6751105/1427878), but a proper DOM parser. – CBroe Jun 14 '22 at 11:12
  • You can try `document.querySelectorAll("path").forEach(p =>{p.removeAttribute("fill");})` This will fill the path with the default black. You can also use `setAttribute` instead of removeAttribute if you want to set the attribute to none or to a different color – enxaneta Jun 14 '22 at 11:29
  • @CBroe the whole string is generated React component that returns SVG element, thus seems not possible using DOM parser. Might be possible if I can get the SVG string only. – Dion Dirza Jun 14 '22 at 11:49
  • _"the whole string is generated React component that returns SVG element"_ - probably not for the purpose of looking at the SVG in text form though, but to do something with that SVG code afterwards - like, insert it into the DOM? – CBroe Jun 14 '22 at 12:28
  • 1
    Like everyone says, use a DOM parser.. hey your Browser actually IS a DOM parser.. and then use ``enxaneta`` removeAttribute code. That is the easiest way. Alas you use React, which means you have to jump through some extra hoops. But same concept applies, let the Browser do the work. Great example where React is the wrong choice, and then needs loads of extra coding. – Danny '365CSI' Engelman Jun 14 '22 at 16:38
  • Actually, this code happens in the component library to generate SVG assets file into React component, thus it is running on NodeJS. – Dion Dirza Jun 15 '22 at 02:24

1 Answers1

2

It's a brittle solution, but if a lookbehind assertion is supported maybe it is enough to lookback for the <path followed by any char except the angle brackets and then match the fill attribute.

In the replacement use an empty string.

(?<=<path\b[^<>]*)\s*\bfill=(["']).*?\1

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70