Use eval to do dynamic string replace - Javascript String Operation

Javascript examples for String Operation:String Replace

Description

Use eval to do dynamic string replace

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript">
    window.onload=function(){//from w w w  .  j  av  a 2 s .com
var str = "<div class=\"~~obj.classname~~\" style=\"~~obj.color~~\">~~obj.content~~</div>";
var opt = {
    obj : {
        classname : 'class',
        color : 'red',
        content: 'content'
    }
}
var str = "'" + str.replace(/~~(.*?)~~/g, "' + opt.$1 + '") + "'";

var result = eval(str);

console.log(result)
    }

      </script> 
   </head> 
   <body>  
   </body>
</html>

Related Tutorials