A few small but crucial changes should get it working.
Firstly, I think there's a tiny mistake in your str
. For example, you have Button_2
towards the end of str
but I'm assuming you just want this to be Button
and for your replace
function to take care of the incrementing. Otherwise, the result would be Button_2_1
... So I'm assuming you want str
to be this:
str = 'View{Image{BackgroundImage: Image.png;Position: 0, 0;Width: 320;Height: 480;}Button{BackgroundImage: ButtonTop.png;Position: 61, 83;Width: 217;Height: 58;}Button{BackgroundImage: ButtonBottom.png;Position: 21, 303;Width: 217;Height: 58;}}'
If that's then right here's the corrected code (which I hope will work for you), with the explanation after:
var i = {};
str = str.replace(/(\w+){/g, function (m, p1) {
i[p1] = (i[p1] || 0) + 1;
return p1 + "_" + i[p1].toString() + ":{";
});
In the original code you had \S
in the parentheses but this is too general, as it will capture even the opening curly brace {
. In regexp, a capital \S
means any character that is not a space. A lowercase \w
will find alphanumeric characters so this is probably what you want to capture the word View
, and Image
, etc. So now any alphanumeric part of the string followed directly (no spaces) by an opening curly brace will be replaced with an underscore and a number, which increments with each instance of that item.
I wasn't sure if you actually want the colon :
to appear after each number so I have left it in but if you actually don't want it just replace the return statement with return p1 + "_" + i[p1].toString() + "{";
Otherwise, if you're happy with above (colon included), this is the resulting string:
View_1:{Image_1:{BackgroundImage: Image.png;Position: 0, 0;Width: 320;Height: 480;}Button_1:{BackgroundImage: ButtonTop.png;Position: 61, 83;Width: 217;Height: 58;}Button_2:{BackgroundImage: ButtonBottom.png;Position: 21, 303;Width: 217;Height: 58;}}
Which I think is what you wanted. I've set up a fiddle so you can see the corrected code in action and have a play.
Hope this helps.