I have hundreds of strings, in which I conditionally need to add or remove something. To add a bit more context, this is in fact stringified SVGs, where I want to add/remove attributes to certain nodes. Since I don't have the luxury of a DOM at any stage of this process, and both the input and desired output is a string, I want to do this with a string replacement using RegEx.
The logic is: any substring which looks like an SVG element (path
, circle
etc.). which doesn't have a stroke
attribute needs to have it added with a value of none
.
Example input:
<svg>
<path d="..." fill="black" />
<path d="..." stroke="black" />
<circle cx="50" cy="50" r="50" fill="black" />
</svg>
Desired output:
<svg>
<path d="..." fill="red" stroke="none" />
<path d="..." stroke="black" />
<circle cx="50" cy="50" r="50" fill="black" stroke="none" />
</svg>
Note that the first <path>
and the <circle>
has a stroke="none"
added, while the other path
remains unchanged.
What I've tried so far:
const matcher = /(?<=path)((?!stroke=).)*(?=\/>)/g
const newSvg = oldSvg.replace(matcher, ' $1 stroke=\"none\" ')
Problems
- I think this is really close , but the output is wrong:
<path " stroke="none" />
(all attributes removed and a"
character is added). - This only matches
path
elements. I tried something like(?<=(path|circle))
, but it seems not to be valid.
What am I doing wrong?