2

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".

Brian Kohrs
  • 279
  • 3
  • 9

8 Answers8

7
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"

pylover
  • 7,670
  • 8
  • 51
  • 73
  • Ideally that'd replace `#{...}` to avoid mangling strings that might contain curly braces. For instance, a JavaScript code snippet. – tadman Apr 13 '12 at 16:31
  • no problem, no matter, this just search for {number} and nothing else. – pylover Apr 13 '12 at 16:33
1

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 }"
Community
  • 1
  • 1
Matheus Moreira
  • 17,106
  • 3
  • 68
  • 107
1

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

peter
  • 41,770
  • 5
  • 64
  • 108
0
var myStr = [];

myStr.push('something')

console.log(myStr.join(""))
elmuchacho
  • 424
  • 3
  • 8
0

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.

Lucero
  • 59,176
  • 9
  • 122
  • 152
0

"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.

0

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.

Community
  • 1
  • 1
Dan Tao
  • 125,917
  • 54
  • 300
  • 447
0

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

jturi
  • 1,615
  • 15
  • 11