Does JavaScript support substitution/interpolation?

Overview


I'm working on a JS project, and as it's getting bigger, keeping strings in good shape is getting a lot harder. I'm wondering what's the easiest and most conventional way to construct or build strings in JavaScript.

My experience so far:

String concatenation starts looking ugly and becomes harder to maintain as the project becomes more complex.

The most important this at this point is succinctness and readability, think a bunch of moving parts, not just 2-3 variables.

It's also important that it's supported by major browsers as of today (i.e at least ES5 supported).

I'm aware of the JS concatenation shorthand:

var x = 'Hello'; var y = 'world'; console.log(x + ', ' + y); 

And of the String.concat function.

I'm looking for something a bit neater.

Ruby and Swift do it in an interesting way.

Ruby

var x = 'Hello' var y = 'world' print "#{x}, #{y}" 

Swift

var x = "Hello" var y = "world" println("\(x), \(y)") 

I was thinking that there might be something like that in JavaScript maybe something similar to sprintf.js.

Question


Can this be done without any third party library? If not, what can I use?

0

7 Answers

With ES6, you can use

ES5 and below:

  • use the + operator

    var username = 'craig'; var joined = 'hello ' + username; 
  • String's concat(..)

    var username = 'craig'; var joined = 'hello '.concat(username); 

Alternatively, use Array methods:

  • join(..):

    var username = 'craig'; var joined = ['hello', username].join(' '); 
  • Or even fancier, reduce(..) combined with any of the above:

    var a = ['hello', 'world', 'and', 'the', 'milky', 'way']; var b = a.reduce(function(pre, next) { return pre + ' ' + next; }); console.log(b); // hello world and the milky way 
3

I'm disappointed that nobody in the other answers interpreted "best way" as "fastest way"...

I pulled the 2 examples from here and added str.join() and str.reduce() from nishanths's answer above. Here are my results on Firefox 77.0.1 on Linux.


Note: I discovered while testing these that if I place str = str.concat() and str += directly before or after each other, the second one always performs a fair bit better... So I ran these tests individually and commented the others out for the results...

Even still, they varied widely in speed if I reran them, so I measured 3 times for each.

1 character at a time:

  • str = str.concat(): 841, 439, 956 ms / 1e7 concat()'s
  • ............str +=: 949, 1130, 664 ms / 1e7 +='s
  • .........[].join(): 3350, 2911, 3522 ms / 1e7 characters in []
  • .......[].reduce(): 3954, 4228, 4547 ms / 1e7 characters in []

26 character string at a time:

  • str = str.concat(): 444, 744, 479 ms / 1e7 concat()'s
  • ............str +=: 1037, 473, 875 ms / 1e7 +='s
  • .........[].join(): 2693, 3394, 3457 ms / 1e7 strings in []
  • .......[].reduce(): 2782, 2770, 4520 ms / 1e7 strings in []

So, regardless of whether appending 1 character at a time or a string of 26 at a time:

  • Clear winner: basically a tie between str = str.concat() and str +=
  • Clear loser: [].reduce(), followed by [].join()

My code, easy to run in a browser console:

{ console.clear(); let concatMe = 'a'; //let concatMe = 'abcdefghijklmnopqrstuvwxyz'; //[].join() { s = performance.now(); let str = '', sArr = []; for (let i = 1e7; i > 0; --i) { sArr[i] = concatMe; } str = sArr.join(''); e = performance.now(); console.log(e - s); console.log('[].join(): ' + str); } //str += { s = performance.now(); let str = ''; for (let i = 1e7; i > 0; --i) { str += concatMe; } e = performance.now(); console.log(e - s); console.log('str +=: ' + str); } //[].reduce() { s = performance.now(); let str = '', sArr = []; for (let i = 1e7; i > 0; --i) { sArr[i] = concatMe; } str = sArr.reduce(function(pre, next) { return pre + next; }); e = performance.now(); console.log(e - s); console.log('[].reduce(): ' + str); } //str = str.concat() { s = performance.now(); let str = ''; for (let i = 1e7; i > 0; --i) { str = str.concat(concatMe); } e = performance.now(); console.log(e - s); console.log('str = str.concat(): ' + str); } 'Done'; }
1
var descriptor = 'awesome'; console.log(`ES6 is ${descriptor}!`); 

More:

3

I think replace() deserves mentioning here.

During some conditions, the replace method can serve you well when building strings. Specifically, obviously, when your injecting a dynamic part into an otherwise static string. Example:

var s = 'I am {0} today!'; var result = s.replace('{0}', 'hungry'); // result: 'I am hungry today!' 

The placeholder which to replace can obviously be anything. I use "{0}", "{1}" etc out of habit from C#. It just needs to be unique enough not to occur in the string other than where intended.

So, provided we can fiddle with the string parts a bit, OPs example could be solved like this too:

var x = 'Hello {0}'; var y = 'World'; var result = x.replace('{0}', y); // result: 'Hello World'. -Oh the magic of computing! 

Reference for "replace":

You could use the concat function.

var hello = "Hello "; var world = "world!"; var res = hello.concat(world); 
5

You could use Coffeescript, it's made to make javascript code more concise.. For string concatenation, you could do something like this:

first_name = "Marty" full_name = "#{first_name} McFly" console.log full_name 

Maybe you can start here to see what's offered by coffescript..

**Top 3 Practical Ways to Perform Javascript String Concatenation** 1) Using the concat() method let list = ['JavaScript',' ', 'String',' ', 'Concatenation']; let result = ''.concat(...list); console.log(result); Output: JavaScript String Concatenation 2) Using the + and += operators enter code here The operator + allows you to concatenate two strings. For example: let lang = 'JavaScript'; let result = lang + ' String'; console.log(result); Output: JavaScript String 3) Using template literals`enter code here` ES6 introduces the template literals that allow you to perform string interpolation. The following example shows how to concatenate three strings: let navbarClass = 'navbar'; let primaryColor = 'primary-color'; let stickyClass = 'sticky-bar'; let className = `${navbarClass} ${primaryColor} ${stickyClass}`; console.log(className); Output: navbar primary-color stickyBar