When I’m writing Javascript code, I feel miss Ruby’s #{} method.So I implement it in JS.
But this code is not clean and beautiful. I want to make this method safe, But I can’t do it.
Do you have any idea that this code makes safe or beautiful? Thanks in advance.
String.prototype.to_s = function(){
var str = this.toString();
// convert function is bad because it use eval...
var convert = function(s){
return eval(s);
};
// It's slower because call ReGexp method too many times.
while(/#{(\w+)}/.test(str)){
var matchStr =RegExp.$1;
var str = str.replace(/#{(\w+)}/,convert(matchStr));
}
return str;
};
var name = "nobi";
var age = 23;
var body = "I'm #{name} and I am #{age} years old".to_s();
// I'm nobi and I am 23 years old.
console.log(body);
That sort of hack can’t be made “beautiful” – it doesn’t even work for non-globals. Given ES6 support, though, you don’t need the hack; string interpolation is now a part of the language.
Failing that, string concatenation is often readable enough with ES5 and earlier:
CoffeeScript, a language that compiles to JavaScript, also supports this feature.