Skip to content

Instantly share code, notes, and snippets.

@nandobang
Created November 29, 2012 11:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nandobang/4168440 to your computer and use it in GitHub Desktop.
Save nandobang/4168440 to your computer and use it in GitHub Desktop.
JavaScript in-string variables

JS in-string variables

We all love JS, don't we? Yes, we do. But, unfortunately, JS does not allow us to insert variables inside a string. We must close our quotes, concatenate with a + operator, and live our lives. What this tiny script does is replace anything inside #{ } for a variable. Ruby users know what this is.

Example

Let's say, you have two variables:

var mood = "nice";
var person = "Bob";

And this is the string you want to format:

var myString = "This is #{mood}, isn't it, #{person}?";

You would simply do a:

myString.pretify();

And this is your result:

"This is nice, isn't it, Bob?"

I find it pretty fast-forward, and useful :)

String.prototype.pretify = function()
{
var matches = this.match(/\#\{.+?\}/g);
var pretified = this;
for (var m in matches)
{
var match = matches[m];
var evalCode = match.substr(2, match.length - 3);
var result = eval(evalCode);
pretified = pretified.replace(match, result);
}
return pretified;
};
@endel
Copy link

endel commented Nov 29, 2012

Eval is evil!

"#{alert('it beats you!')}".pretify()

@bloodyowl
Copy link

Wouldn't this be better if passing an object as argument ? (also eval makes you pass globals, which is not good at all)

String.prototype.prettify = function(o){
  return this.replace(/\#\{(\w+?)\}/g, function(a,b){return o[b]})
}

If you are interested, I builded a little more flexible one : http://mlb.tl/LGDK

Cheers

@fuadsaud
Copy link

fuadsaud commented Dec 3, 2012

@endel I think eval is the right thing here. You should be able to put any expression that returns something to interpolate. And function calls are expressions (even when returning undefined), but that's up to the programmer.

So it's more like: eval is dangerous, programmers are evil. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment