Anything similar in javascript to ruby's #{value} (string interpolation)
ES6 Update:
ES6 added template strings, which use backticks (`) instead of single or double quotes. In a template string, you can use the ${}
syntax to add expressions. Using your example, it would be:
string_needed = `prefix.....${topic}suffix....${name}testing`
Original answer:
Sorry :(
I like to take advantage of Array.join:
["prefix ....", topic, "suffix....", name, "testing"].join("")
or use String.concat
String.concat("a", 2, "c")
or you could write your own concatenate function:
var concat = function(/* args */) {
/*
* Something involving a loop through arguments
*/
}
or use a 3rd-party sprintf
function, such as http://www.diveintojavascript.com/projects/javascript-sprintf
You could consider using coffeescript to write the code (which has interpolation like Ruby ie #{foo}).
It 'compiles' down to javascript - so you will end up with javascript like what you've written, but without the need to write/maintain the +++ code you're tired of
I realize that asking you to consider another language is on the edge of being a valid answer or not but considering the way coffeescript works, and that one of your tags is Ruby, I'm hoping it'll pass.
As a Javascript curiosity, you can implement something that basically does Ruby-like interpolation:
sub = function(str) {
return str.replace(/#\{(.*?)\}/g,
function(whole, expr) {
return eval(expr)
})
}
js> y = "world!"
world!
js> sub("Hello #{y}")
Hello world!
js> sub("1 + 1 = #{1 + 1}")
1 + 1 = 2
Using it on anything but string literals is asking for trouble, and it's probably quite slow anyways (although I haven't measured). Just thought I'd let you know.