Is there a better way to build strings in JavaScript than doing string concatination?
It would make my code cleaner if I could do something like ruby where you can expand variables in a string instead of doing lots of "foo" + bar + "baz".
Is there a better way to build strings in JavaScript than doing string concatination?
It would make my code cleaner if I could do something like ruby where you can expand variables in a string instead of doing lots of "foo" + bar + "baz".
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
console.log("{0} bar {1}.".format("foo","baz"));
Will produce:
"foo bar baz"
Chris Nielsen has provided a pure-JavaScript solution in this answer:
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
alert("I'm {age} years old!".supplant({ age: 29 }));
alert("The {a} says {n}, {n}, {n}!".supplant({ a: 'cow', n: 'moo' }));
You could also use CoffeScript, which is a language that compiles to JavaScript. It supports string interpolation:
author = "Wittgenstein"
quote = "A picture is a fact. -- #{ author }"
sorry guys but all this is not very the ruby way, here is a basic p equivalent, sorry for the eval, that surely can be done better.. if you just want the concatenation, just replace the document.write by return in the first solution
function p(str){
document.write(str.replace(/#{(\w)}/g, function(match, s){return eval(s)})+"<br>");
}
String.prototype.p = function() {
return this.replace(/#{(\w)}/g, function(match, s){return eval(s)})+"<br>";
};
var f="foo", b="bar"
p("#{f} #{b}")
document.write("#{f} #{b}".p());
=> foo bar
=> foo bar
EDIT: i added a prototype version, had some difficulties with that one
If you deal with lots of strings then using an array where you push
the string parts and at the end join
them (with an empty string as delimiter) seems to be the most efficient across platforms.
"Is there a JavaScript equivalent of rubys
“#{}”
sequences?"
With respect to an equivalent, no. JavaScript natively does not have string interpolation. Though you could use a function to replicate it to some degree.
pylover's answer will give you something like what you want.
You might also look into CoffeeScript, which is a nice language that compiles to JavaScript and has string interpolation, among other (perhaps too many) features.
It is called syntactic sugar.
var a = 2;
var b = 4;
var c = "together";
var text = `Add ${a*b} elements ${c}.`;
console.log(text)
// "Add 8 elements together." (515,988,604 op/sec)
vs.
var text = "Add" + " " + a*b + " " + "elements" + " " + c + ".";
console.log(text)
// "Add 8 elements together." (511,188,184 op/sec 0.73% slower)
First method is faster and better to read.
Performance tested here: JSPerf string test