blti_w
Last Updated: February 25, 2016
·
4.696K
· fuadsaud
22e767367fe9c51fc5d22af7a631c424

Dumb JavaScript string interpolation

If you're like me and don't like to concatenate strings (it's ugly!), you may enjoy this simple solution for interpolating expressions with your JS strings:

 if (!String.prototype.interpolate) {
     String.prototype.interpolate = function() {
       var i = 0, text = this;

       for (i = 0; i < arguments.length; i++) {
         text = text.replace('%', arguments[i]);
       }

       return text;
   };
}

then you can just:

var input = 'coming!';
'Winter is %'.interpolate(input);

it's cleaner and easier to maintain than opening and closing strings and adding those '+' operators. There's no way to escape the '%' character though :(

You can also choose a shorter name than interpolate, if you like shorter things.

Say Thanks
Respond

2 Responses
Add your response

1869
Photo on 08.01.2013 at 04.15

Coffeescript :)

over 1 year ago ·
1872
22e767367fe9c51fc5d22af7a631c424

@sheerun I tried to like coffeescript, but until now, it didn't convinced me. Despite the fact I love ruby syntax, the coffeescript approach seems problematic sometimes :\

over 1 year ago ·