Home > Web Front-end > JS Tutorial > body text

js replacement_javascript skills

WBOY
Release: 2016-05-16 19:06:04
Original
1223 people have browsed it

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:

Copy code The code is as follows:

<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:
Copy code The code is as follows:

<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>
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!