我有以下代码解析此字符串并将其转换为Object。因为其中有重复的键,我需要为每个键附加一个递增的数字。
var str = 'View\n{\n Name: View1;\n Image\n {\n BackgroundImage: Image.gif;\n Position: 0, 0;\n Width: 320;\n Height: 480;\n }\n\n Button\n {\n BackgroundImage: Button.gif;\n Transition: View2;\n Position: 49, 80;\n Width: 216;\n Height: 71;\n }\n\n Button\n {\n BackgroundImage: Button2.gif;\n Position: 65, 217;\n Width: 188;\n Height: 134;\n }\n\n Label\n {\n Position: 106, 91;\n Width: 96;\n Height: 34;\n Text: "Button";\n FontSize: 32;\n Color: 0.12549, 0.298039, 0.364706, 1;\n }\n Scroll\n {\n Position: 106, 91;\n Width: 96;\n Height: 34;\n Button{\n BackgroundImage: Button2.gif;\n Position: 65, 217;\n Width: 188;\n Height: 134;\n }\n Button{\n BackgroundImage: Button2.gif;\n Position: 65, 217;\n Width: 188;\n \n Height: 134;\n }\n\n }\n\n}';
str = str.replace(/(\w+)\s*\{/g, "$1:{"); // add in colon after each named object
str = str.replace(/\}(\s*\w)/g, "},$1"); // add comma before each new named object
str = str.replace(/;/g, ","); // swap out semicolons with commas
str = str.replace(/,(\s+\})/g, "$1"); // get rid of trailing commas
str = str.replace(/([\d\.]+(, [\d\.]+)+)/g, "[$1]"); // create number arrays
str = str.replace(/"/g, ""); // get rid of all double quotes
str = str.replace(/:\s+([^\[\d\{][^,]+)/g, ':"$1"'); // create strings
$("pre").html(str);
在这个工作演示中:http://jsfiddle.net/T59fL/2/ 我需要将增加的数字附加到其末尾带有':{'的任何内容中。即视图,按钮,按钮,图像等将变为View1,Button1,Button2,Image1等等。
答案 0 :(得分:0)
解决了jsfiddle.net/GaX6E/2
var i = 0;
str = str.replace(/([^:]+):{/g, function(m, p1) { return p1 + "_" + (++i).toString() + ":{"; });