JS Replacement _javascript Tips

Source: Internet
Author: User
Problem: The type of (()) () () () () ()) (()) replaced by [][][[[]][]], which handles parentheses
Author: infinte
Requirements:
[1] supports arbitrary "brackets", which means "<>{}" () ... or XML-like:<a></a>, [Cc][cc:over], {TTT] [TTT}
[2] strictly in accordance with the hierarchy, that is (a) B (c (d) e) replaced by [a]b[c[d]e] rather than [A]b[c (d]e) (end too early)
[3] The opening parenthesis is more than the right parenthesis and retains the extra brackets, namely: () () (() ()) (() ()) →[][] [[[]]
[4] The closing parenthesis is more than the left parenthesis, leaving the extra brackets, i.e. (() () (() ()))))))

Scenario One: Using stacks
Author: Winter
Code:
Copy Code code as follows:

<script>
var Strarr = "() () ((() ())";

function Change (str)
{
var a=str.split ("");
var c=0;
var stack=[];
var match={
"(":")",
"{":"}",
"<": ">",
"【":"】"
}
for (Var i=0;i<a.length;i++)
if (Match[a[i]]) {
Stack.push ([a[i],i]);
}
else if (a[i]== ")" | | a[i]== "}" | | a[i]== ">" | | a[i]== "" ") {
if (!stack.length) continue;
var tmp=stack.pop ();
if (Match[tmp[0]]==a[i]) a[i]= "]", a[tmp[1]]= "[";
else Stack.push (TMP);
}
Return A.join ("");
}
Alert (change (Strarr));
</script>

Programme II: Use of regular
Author: Moon Shadow
Code:
Copy Code code as follows:
<script> 
var strarr = " () () ((()) ";  
var o = strarr; 
var r = o; 
do{ 
 o  ;= r; 
 r = o.replace (/\ ([^ ()]*) \)/g,function (s,a) {return  ' [' +a+ '] '}); 
}while (o!=r); 
Alert (r); 
</script> 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.