Home > Software design >  js regex to wrap numbers and variables in string in span tags
js regex to wrap numbers and variables in string in span tags

Time:11-06

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related