Errol Fitzgerald Errol Fitzgerald - 8 months ago 35
Javascript Question

How to alter a regex to be non-greedy (JS)

I'm trying to replace

tags with an attribute so they are wrapped in square brackets

data.replace(/<var .*?="">(\d+)<\/var>/ig, '[[[$1]]]');

but this will not work if there are multiple
tags. For example,

<var id-0=""></var> responds <span id-1="">in <var num="">1</var> days</span>

will result in

[[[1]]] days</span>

but the result I need is

<var id-0=""></var> responds <span id-1="">in [[[1]]] days</span></strong>


using this <var [^=]*="">(\d+)<\/var>

regex101 - 1

in case there would be more than one attribute or the attribute has value like num="something" then the above wouldn't work, instead, use this <var( [^=]*="[^"]*")*>(\d+)<\/var> with [[[$2]]] for substitution.

regex101 - 2