Reputation: 1469
i have a string like so:
${1}${2}${3}${4}%9${5}00
And I'm wanting to wrap all the numbers and vars in span tags But the issue is there can be an unlimited number of "${1}" variables in this string.
The current regex I'm using is
str.replace(/([0-9\/\+\(\)\%\-\*v]{1})/g, '<span>$1</span>')
But the problem with this regex is it wraps the $, { and } in a separate span tag. I'm wanting to wrap the "${1}" in its own span tag.
How would I do this and if possible can you explain the regex.
Thanks
Working example:
et str = '${1}${2}${3}${4}%9${5}00';
let copy = str.replace(/(\$\{\d+\}|[\d/+()%*v-])/g, '<span>$1</span>');
console.log('Copy: ', copy)
Upvotes: 0
Views: 111
Reputation: 2410
IIRC,
How about a simple regex with
str.replace(/(\$\{\d\})/g, '<span>$1</span>')
The output is:
'<span>${1}</span><span>${2}</span><span>${3}</span><span>${4}</span>%9<span>${5}</span>00'
It matches ${<digit>}
, if you want to match more digits, for examples ${11}
or ${123}
, you can simply put \d+
in place of \d
.
Here is the updated version matching the special characters as well with different capture groups.
const str = "${1}${2}${3}${4}%9${5}00"
const out = str.replace(/(\$\{\d+\}|\%|\d)/g, '<span>$1</span>')
console.log(out)
Upvotes: 2
Reputation: 13641
let str = '${1}${2}${3}${4}%9${5}00';
str = str.replace(/\$\{\d+\}|[\d/+()%*v-]/g, '<span>$&</span>');
console.log(str);
The regex will match either of two alternatives separated by |
.
First, it will try to match a "variable" using \${\d+}
then it will try to match a number or symbol using [\d\/+()%*v-]
.
Whatever is matched is then referenced using $&
(the full match) in the replacement string.
Upvotes: 1