Home > Net >  Regex to remove attribute from specific SVG element in string
Regex to remove attribute from specific SVG element in string

Time:06-15

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

CodePudding user response:

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

  • Related