Last Updated: February 25, 2016
·
6.038K
· fuadsaud

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.

2 Responses
Add your response

Coffeescript :)

over 1 year ago ·

@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 ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside