Rob
Rob

Reputation: 11487

Wrap Numbers in Brackets using javascript .replace regex

I have this String that I am trying to wrap Brackets around the arrays of numbers following 'Position' and Color.

str = 'Label_3_1:{Position: 115,234,Width: 126,Height: 20,Text:"Another Button",FontSize: 18,Color: 0,0,0,1}'

I can use this regex to do it, but only if the numbers have a space after each comma

str = str.replace(/([\d\.]+(, [\d\.]+)+)/g, "[$1]");

I am trying to make it work without any spaces.

Output should look like this

str = 'Label_3_1:{Position: 115,234,Width: 126,Height: 20,Text:"Another Button",FontSize: 18,Color: [0, 0, 0, 1] }'

Upvotes: 1

Views: 1761

Answers (1)

Ray Shih
Ray Shih

Reputation: 933

by add \s*, it works

str.replace(/([\d\.]+(,\s*[\d\.]+)+)/g, "[$1]");

And this is the result:

"Label_3_1:{Position: [115,234],Width: 126,Height: 20,Text:"Another Button",FontSize: 18,Color: [0,0,0,1]}"

Upvotes: 1

Related Questions