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 :)
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
Best
#Javascript
Authors
Related Tags
#javascript
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#