RegEx Replacement in JavaScript - Javascript String Operation

Javascript examples for String Operation:String Replace

Description

RegEx Replacement in JavaScript

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;//  w  ww  .j a v a 2 s .  c  o  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