Question: Just replace ()()()(())()) with [][][[[]][]], which is used to handle bracket matching
Author: infinte
Requirements:
[1] Supports any "brackets", that is, you can use []<>{}()...or XML-like: , [cc] [cc:over], {ttt] [ttt}
[2] Strictly match levels, that is, (a)b(c(d)e) is replaced by [a]b[c[d]e] instead of [a]b[c(d]e) (It ends too early)
[3] When there are more left brackets than right brackets, keep the extra brackets, that is: ()()((()()) → [ ][]([[][]]
[4] There are more right brackets than left brackets, keep the extra brackets, that is: (()()(()()))))) → [[][ ][[][]]])))
Option 1: Use stack
Author: winter
Code:
<script> <br>var strArr = "()()((()())"; <br><br>function change(str) <br>{ <br> var a=str.split(""); <br> var c=0; <br> var stack=[]; <br> var match={ <br> "(":")", <br> "{":"}", <br> "<":">", <br> "【":"】" <br> } <br> for(var i=0;i<a.length;i ) <BR> if(match[a[i]]){ <BR> stack.push([a[i],i]); <BR> } <BR> else if(a[i]==")"||a[i]=="}"||a[i]==">"||a[i]=="]") { <br> if(!stack.length)continue; <br> var tmp=stack.pop(); <br> if(match[tmp[0]]==a[i])a[i]=" ]",a[tmp[1]]="["; <br> else stack.push(tmp); <br> } <br> return a.join("") ; <br>} <br>alert (change(strArr)); <br></script>
Option 2: Use regular expressions
Author: Yueying
Code:
<script> <br>var strArr = "()()((()()) "; <br>var o = strArr; <br>var r = o; <br>do{ <br> o = r; <br> r = o.replace(/(([^()]*)) /g,function(s,a){return '[' a ']'}); <br>}while(o!=r); <br>alert(r); <br></script>