Create string template with String regex - Javascript String Operation

Javascript examples for String Operation:String Replace

Description

Create string template with String regex

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
   </head> 
   <body> 
      <script type="text/javascript">
String.prototype.interpolate = (function () {
    var re = /\[(.+?)\]/g;//from   w w w.  j  a v a  2s.co  m
    return function (o) {
        return this.replace(re, function (_, k) {
            return o[k];
        });
    }
}());
var obj = {
    hey: 'Hey',
    what: 'world',
    when: 'today'
}
document.write(
    '[hey]-hey, this is [what] [when]!'.interpolate(obj)
);

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

Related Tutorials