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.
Written by Fuad Saud
Related protips
2 Responses
Coffeescript :)
@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 :\
Have a fresh tip? Share with Coderwall community!
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