Use javascript to replace perl-style Variables

Source: Internet
Author: User

The replacement of perl-style variables provides better readability. In common javascript programming, there are many + numbers, which are dazzling. Good news: we can use regular expressions to convert programming styles.

The following example specifies that the string in $ {} is the variable name and defines the varReplace prototype function to replace the variable:

 
 
  1. String. prototype. varReplace = function (){
  2. Var pttrn =/\$ {(\ w +)}/g;
  3. Return this. replace (pttrn, function (a, B) {return eval (B )});
  4. }
  5.  
  6. Var myVar1 = "#00ff11 ";
  7. Var myVar2 = "test ";
  8. Var myStr1 = '<font color = "$ {myVar1}"> <B >$ {myVar2} </B> </font>'; // perl Style
  9. Var myStr2 = '<font color = "' + myVar1 + '"> <B>' + myVar2 + '</B> </font>'; // javascript Style
  10.  
  11. IJs.pt ("myStr1.varReplace ()");
  12. IJs.pt ("myStr2 ");
Debugging information:
MyStr1.varReplace () Test
MyStr2 Test 

This article is from the iData blog, please be sure to keep this source http://idata.blog.51cto.com/4581576/1108042

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.